@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
@@ -1,14 +1,15 @@
1
1
  import { z } from 'zod';
2
2
  import { webSearchConfig } from './user-config.js';
3
3
  import { parse, stringify } from 'smol-toml';
4
- import { DEFAULT_MODE_REF, RuntimeError, lookupModelMetadata, normalizeProviderBaseUrl, normalizeProviderProtocol, providerProtocolInputs, validateTeamConfig, validateWorkSubpath, } from '@saturn-universe/core';
5
- import { credentialRefSchema, providerIdSchema } from '@saturn-universe/protocol';
6
- import { maxShellTimeoutMs } from '@saturn-universe/tools';
4
+ import { DEFAULT_MODE_REF, RuntimeError, lookupModelMetadata, openCodeClientHeaders, providerPresets, validateTeamConfig, validateWorkSubpath, } from '@saturn-universe/core';
5
+ import { credentialRefSchema, providerBaseUrlSchema, providerIdSchema, providerModelIdSchema, providerModelRouteSchema, } from '@saturn-universe/protocol';
7
6
  import { capabilities, defaultCapabilities } from './configuration.js';
8
7
  import { mcpServersSchema } from './mcp-configuration.js';
9
8
  import { modeDefinitionsSchema, skillDefinitionsSchema } from './context-extensions.js';
10
9
  import { configurationTable } from './plugin-configuration.js';
11
- import { configuredRunBudgetShape, resolveRunBudget } from './run-budget.js';
10
+ import { configuredRunBudgetShape, hardLimits, resolveRunBudget, } from './run-budget.js';
11
+ import { resolveRetryPolicy } from './runtime-tuning.js';
12
+ export { hardLimits } from './run-budget.js';
12
13
  const id = z.string().trim().min(1).max(200);
13
14
  const positive = z.number().int().positive().safe();
14
15
  const nonnegativeNumber = z.number().nonnegative().finite();
@@ -19,19 +20,12 @@ const pricingSchema = z.strictObject({
19
20
  output_per_million: nonnegativeNumber,
20
21
  });
21
22
  const codecVersion = z.union([z.literal(1), z.literal(2)]);
22
- const baseUrl = z.string().transform((value, ctx) => {
23
- const url = normalizeProviderBaseUrl(value);
24
- if (url !== undefined)
25
- return url;
26
- ctx.addIssue({ code: 'custom', message: 'Invalid endpoint' });
27
- return z.NEVER;
28
- });
29
23
  const profile = z
30
24
  .strictObject({
31
25
  provider_id: id,
32
26
  revision: id,
33
27
  codec_version: codecVersion,
34
- base_url: baseUrl,
28
+ base_url: providerBaseUrlSchema,
35
29
  model_id: id,
36
30
  credential_ref: credentialRefSchema,
37
31
  default_reasoning_effort: id.optional(),
@@ -39,21 +33,6 @@ const profile = z
39
33
  pricing: pricingSchema.optional(),
40
34
  })
41
35
  .refine((value) => value.codec_version !== 2 || value.revision !== '1');
42
- export const hardLimits = {
43
- maxModelAttempts: 10000,
44
- maxToolCalls: 10000,
45
- maxSteps: 20000,
46
- maxTotalTokens: 10000000,
47
- subagentMaxModelAttempts: 10000,
48
- wallTimeMs: 86400000,
49
- subagentWallTimeMs: 86400000,
50
- modelTimeoutMs: 600000,
51
- streamIdleTimeoutMs: 600000,
52
- requestTotalTimeoutMs: 600000,
53
- toolTimeoutMs: 600000,
54
- shellTimeoutMs: maxShellTimeoutMs,
55
- maxParallelTools: 64,
56
- };
57
36
  const runDefaults = z.strictObject({
58
37
  mode_ref: id.optional(),
59
38
  permission_mode: z.enum(['strict', 'default', 'full']).optional(),
@@ -65,11 +44,8 @@ const runDefaults = z.strictObject({
65
44
  worker_reasoning_effort: id.optional(),
66
45
  reasoning_summary: z.enum(['auto', 'concise', 'detailed']).optional(),
67
46
  ...configuredRunBudgetShape(hardLimits),
68
- model_timeout_ms: positive.max(hardLimits.modelTimeoutMs).optional(),
69
47
  model_idle_timeout_ms: positive.max(hardLimits.streamIdleTimeoutMs).optional(),
70
48
  model_total_timeout_ms: positive.max(hardLimits.requestTotalTimeoutMs).optional(),
71
- tool_timeout_ms: positive.max(hardLimits.toolTimeoutMs).optional(),
72
- max_parallel_tools: positive.max(hardLimits.maxParallelTools).optional(),
73
49
  });
74
50
  const teamPresetSchema = z.strictObject({
75
51
  concurrency: positive.max(16).optional(),
@@ -85,6 +61,7 @@ const teamPresetSchema = z.strictObject({
85
61
  .max(15),
86
62
  });
87
63
  const modelOverride = z.strictObject({
64
+ ...providerModelRouteSchema.shape,
88
65
  context_window: positive.optional(),
89
66
  max_output_tokens: positive.optional(),
90
67
  default_reasoning_effort: id.optional(),
@@ -93,19 +70,23 @@ const modelOverride = z.strictObject({
93
70
  tools: z.boolean().optional(),
94
71
  parallel_tool_calls: z.boolean().optional(),
95
72
  streaming: z.boolean().optional(),
73
+ structured_output: z.boolean().optional(),
96
74
  images: z.boolean().optional(),
97
75
  pricing: pricingSchema.partial().optional(),
98
76
  });
99
77
  const provider = z
100
78
  .strictObject({
101
- base_url: baseUrl,
102
- protocol: z.enum(providerProtocolInputs).transform(normalizeProviderProtocol).optional(),
79
+ ...providerModelRouteSchema.shape,
80
+ base_url: providerBaseUrlSchema,
103
81
  credential_ref: credentialRefSchema,
104
- models: z.array(id.regex(/^[^\u0000-\u001f\u007f]+$/)).min(1),
82
+ models: z.union([
83
+ z.array(providerModelIdSchema).min(1),
84
+ configurationTable(providerModelIdSchema, modelOverride).refine((models) => Object.keys(models).length > 0),
85
+ ]),
105
86
  revision: id.optional(),
106
87
  codec_version: codecVersion.optional(),
107
88
  default_reasoning_effort: id.optional(),
108
- model_overrides: configurationTable(id, modelOverride).optional(),
89
+ model_overrides: configurationTable(providerModelIdSchema, modelOverride).optional(),
109
90
  })
110
91
  .refine((value) => value.codec_version !== 2 || (value.revision ?? '1') !== '1');
111
92
  const catalogSchema = z.strictObject({
@@ -172,13 +153,14 @@ export function parseProviderCatalog(value) {
172
153
  };
173
154
  });
174
155
  for (const [providerId, value] of Object.entries(data.providers ?? {})) {
156
+ const models = Array.isArray(value.models) ? value.models : Object.keys(value.models);
175
157
  if (`${providerId}@${value.revision ?? '1'}`.length > 200 ||
176
- Object.keys(value.model_overrides ?? {}).some((model) => !value.models.includes(model)))
158
+ Object.keys(value.model_overrides ?? {}).some((model) => !models.includes(model)))
177
159
  throw invalid();
178
- for (const modelId of value.models)
160
+ for (const modelId of models)
179
161
  profiles.push(expandProfile(providerId, modelId, value));
180
162
  }
181
- if (!data.providers && !data.profiles)
163
+ if (!data.providers && !data.profiles && !data.modes)
182
164
  throw invalid();
183
165
  const names = new Set();
184
166
  const identities = new Set();
@@ -192,12 +174,8 @@ export function parseProviderCatalog(value) {
192
174
  throw invalid();
193
175
  identities.add(identity);
194
176
  const revisionRef = `${p.providerId}@${p.revision}`;
195
- const binding = JSON.stringify([
196
- p.baseURL,
197
- p.credentialRef,
198
- p.codecVersion,
199
- p.protocol ?? 'openai-responses',
200
- ]);
177
+ const route = providerRoute(p, data.providers);
178
+ const binding = JSON.stringify([route.baseURL, p.credentialRef, p.codecVersion, route.protocol]);
201
179
  if (revisions.has(revisionRef) && revisions.get(revisionRef) !== binding)
202
180
  throw invalid();
203
181
  revisions.set(revisionRef, binding);
@@ -229,14 +207,17 @@ function expandProfile(providerId, modelId, value) {
229
207
  if (name.length > 200)
230
208
  throw invalid();
231
209
  const model = lookupModelMetadata(modelId);
232
- const override = Object.hasOwn(value.model_overrides ?? {}, modelId)
233
- ? value.model_overrides?.[modelId]
234
- : undefined;
210
+ const legacy = value.model_overrides;
211
+ const models = Array.isArray(value.models) ? undefined : value.models;
212
+ const override = {
213
+ ...(legacy && Object.hasOwn(legacy, modelId) ? legacy[modelId] : {}),
214
+ ...(models && Object.hasOwn(models, modelId) ? models[modelId] : {}),
215
+ };
235
216
  const reasoningModel = override?.reasoning_model ?? model?.reasoningModel ?? Boolean(override?.reasoning_efforts?.length);
236
217
  const tools = override?.tools ?? model?.tools ?? defaultCapabilities.tools;
237
218
  const parallelToolCalls = override?.parallel_tool_calls ??
238
219
  (tools && (model?.parallelToolCalls ?? defaultCapabilities.parallelToolCalls));
239
- const protocol = value.protocol ?? 'openai-responses';
220
+ const protocol = override.protocol ?? value.protocol ?? 'openai-responses';
240
221
  const input = override?.pricing?.input_per_million ?? model?.pricing.inputPerMillion;
241
222
  const output = override?.pricing?.output_per_million ?? model?.pricing.outputPerMillion;
242
223
  const cached = override?.pricing?.cached_input_per_million ?? model?.pricing.cachedInputPerMillion;
@@ -248,7 +229,7 @@ function expandProfile(providerId, modelId, value) {
248
229
  providerId,
249
230
  revision: value.revision ?? '1',
250
231
  codecVersion: value.codec_version ?? 1,
251
- baseURL: value.base_url,
232
+ baseURL: override.base_url ?? value.base_url,
252
233
  modelId,
253
234
  credentialRef: value.credential_ref,
254
235
  protocol,
@@ -260,6 +241,7 @@ function expandProfile(providerId, modelId, value) {
260
241
  tools,
261
242
  parallelToolCalls,
262
243
  streaming: override?.streaming ?? model?.streaming ?? defaultCapabilities.streaming,
244
+ structuredOutput: override.structured_output ?? defaultCapabilities.structuredOutput,
263
245
  images: override?.images ?? model?.images ?? defaultCapabilities.images,
264
246
  responses: {
265
247
  ...defaultCapabilities.responses,
@@ -343,24 +325,42 @@ export const profileModel = (p) => ({
343
325
  modelId: p.modelId,
344
326
  profileRef: `${p.providerId}@${p.revision}`,
345
327
  });
328
+ function providerRoute(p, providers) {
329
+ const layered = p.protocol && providers && Object.hasOwn(providers, p.providerId) ? providers[p.providerId] : undefined;
330
+ return {
331
+ baseURL: layered?.base_url ?? p.baseURL,
332
+ protocol: (layered ? layered.protocol : p.protocol) ?? 'openai-responses',
333
+ };
334
+ }
346
335
  export function catalogRegistrations(catalog) {
347
336
  const groups = new Map();
348
337
  for (const p of catalog.profiles) {
349
338
  const ref = profileModel(p).profileRef;
339
+ const route = providerRoute(p, catalog.providers);
340
+ const modelRoute = {
341
+ ...(p.protocol && p.protocol !== route.protocol ? { protocol: p.protocol } : {}),
342
+ ...(p.baseURL !== route.baseURL ? { baseURL: p.baseURL } : {}),
343
+ };
344
+ const previous = groups.get(ref);
345
+ const modelRoutes = {
346
+ ...previous?.modelRoutes,
347
+ ...(Object.keys(modelRoute).length ? { [p.modelId]: modelRoute } : {}),
348
+ };
350
349
  const entry = {
351
350
  id: p.providerId,
352
351
  revision: p.revision,
353
- protocol: p.protocol ?? 'openai-responses',
354
- baseURL: p.baseURL,
352
+ ...route,
355
353
  apiKeyRef: p.credentialRef,
356
- headers: {},
354
+ headers: providerPresets.some((preset) => preset.id === p.providerId && preset.openCodeModelsUrl)
355
+ ? { 'x-opencode-client': { kind: 'literal', value: openCodeClientHeaders['x-opencode-client'] } }
356
+ : {},
357
357
  credentialScopeRef: p.credentialRef,
358
358
  codecId: 'saturn-responses',
359
359
  codecVersion: p.codecVersion,
360
- models: { [p.modelId]: p.capabilities ?? defaultCapabilities },
360
+ models: { ...previous?.models, [p.modelId]: p.capabilities ?? defaultCapabilities },
361
+ ...(Object.keys(modelRoutes).length ? { modelRoutes } : {}),
361
362
  };
362
- const previous = groups.get(ref);
363
- groups.set(ref, previous ? { ...previous, models: { ...previous.models, ...entry.models } } : entry);
363
+ groups.set(ref, entry);
364
364
  }
365
365
  return [...groups.values()];
366
366
  }
@@ -398,6 +398,13 @@ export function selectProfile(catalog, selection) {
398
398
  }
399
399
  export function resolveRunDefaults(model, defaults, options) {
400
400
  const reasoning = resolveDefaultReasoning(defaults, options);
401
+ const limits = resolveRunBudget(defaults && {
402
+ ...defaults,
403
+ stream_idle_timeout_ms: defaults.stream_idle_timeout_ms ?? defaults.model_idle_timeout_ms,
404
+ request_total_timeout_ms: defaults.request_total_timeout_ms ?? defaults.model_total_timeout_ms,
405
+ }, options?.modeBudget, options?.overrides?.limits);
406
+ const modeCompaction = options?.modeRuntime?.compaction;
407
+ const explicitCompaction = options?.overrides?.compaction;
401
408
  return {
402
409
  model,
403
410
  modeRef: defaults?.mode_ref ?? DEFAULT_MODE_REF,
@@ -409,45 +416,39 @@ export function resolveRunDefaults(model, defaults, options) {
409
416
  storage: 'local_stateless',
410
417
  ...(reasoning ? { reasoning } : {}),
411
418
  },
412
- retry: { modelMaxAttemptsPerCall: 3, toolMaxAttemptsPerCall: 1, baseDelayMs: 2000, maxDelayMs: 5000 },
413
- limits: {
414
- ...resolveRunBudget(defaults, options?.modeBudget),
415
- modelTimeoutMs: defaults?.model_timeout_ms ?? 300000,
416
- ...(defaults?.model_idle_timeout_ms !== undefined
417
- ? { streamIdleTimeoutMs: defaults.model_idle_timeout_ms }
418
- : {}),
419
- ...(defaults?.model_total_timeout_ms !== undefined
420
- ? { requestTotalTimeoutMs: defaults.model_total_timeout_ms }
421
- : {}),
422
- toolTimeoutMs: defaults?.tool_timeout_ms ?? 30000,
423
- ...(defaults?.tool_timeout_ms === undefined ? { shellTimeoutMs: maxShellTimeoutMs } : {}),
424
- maxParallelTools: defaults?.max_parallel_tools ?? 4,
425
- },
419
+ limits,
420
+ retry: resolveRetryPolicy(options?.modeRuntime?.retry, options?.overrides?.retry),
421
+ ...(modeCompaction || explicitCompaction
422
+ ? { compaction: { ...modeCompaction, ...explicitCompaction } }
423
+ : {}),
426
424
  };
427
425
  }
428
426
  export function resolveWorkerReasoning(config, capabilities) {
429
- const effort = config.workerReasoningEffort;
430
- const responses = capabilities?.responses;
431
- if (!effort)
427
+ const defaults = config.workerReasoningDefaults;
428
+ const effort = (defaults?.explicitEffort ? undefined : defaults?.modeEffort) ?? config.workerReasoningEffort;
429
+ if (!effort && !defaults)
432
430
  return config;
433
- if (effort === 'off' || effort === 'none') {
434
- const { reasoning: _removed, ...restResponses } = config.responses;
431
+ const { reasoning, ...restResponses } = config.responses;
432
+ const fallback = defaults ? defaults.reasoning : reasoning;
433
+ const baseResponses = { ...restResponses, ...(fallback ? { reasoning: fallback } : {}) };
434
+ const responses = capabilities?.responses;
435
+ if (effort === 'off' || effort === 'none')
435
436
  return { ...config, responses: restResponses };
436
- }
437
- if (!responses?.reasoningModel ||
437
+ if (!effort ||
438
+ !responses?.reasoningModel ||
438
439
  (responses.reasoningEfforts.length > 0 && !responses.reasoningEfforts.includes(effort)))
439
- return config;
440
+ return { ...config, responses: baseResponses };
440
441
  return {
441
442
  ...config,
442
- responses: { ...config.responses, reasoning: { ...config.responses.reasoning, effort } },
443
+ responses: { ...baseResponses, reasoning: { ...fallback, effort } },
443
444
  };
444
445
  }
445
- function resolveDefaultReasoning(defaults, options) {
446
+ export function resolveDefaultReasoning(defaults, options) {
446
447
  const caps = options?.capabilities?.responses;
447
448
  if (!caps?.reasoningModel)
448
449
  return undefined;
449
450
  const supportedEfforts = caps.reasoningEfforts;
450
- const requestedEffort = defaults?.reasoning_effort ?? options?.profileReasoningEffort;
451
+ const requestedEffort = options?.modeMainReasoningEffort ?? defaults?.reasoning_effort ?? options?.profileReasoningEffort;
451
452
  if (requestedEffort === 'off' || requestedEffort === 'none')
452
453
  return undefined;
453
454
  const effort = requestedEffort && (!supportedEfforts.length || supportedEfforts.includes(requestedEffort))
@@ -1,5 +1,6 @@
1
- import type { ModeLimitsConfig, RuntimeLimits } from '@saturn-universe/core';
1
+ import type { ModeLimitsConfig, RuntimeLimits, RuntimeTimingLimits } from '@saturn-universe/core';
2
2
  import { z } from 'zod';
3
+ export declare const hardLimits: Required<RuntimeLimits>;
3
4
  declare const budgetFields: {
4
5
  readonly maxModelAttempts: "max_model_attempts";
5
6
  readonly maxToolCalls: "max_tool_calls";
@@ -9,16 +10,38 @@ declare const budgetFields: {
9
10
  readonly wallTimeMs: "wall_time_ms";
10
11
  readonly subagentWallTimeMs: "subagent_wall_time_ms";
11
12
  };
12
- type BudgetField = keyof typeof budgetFields;
13
- type ConfiguredBudgetField = (typeof budgetFields)[BudgetField];
14
- type ConfiguredRunBudget = Partial<Record<ConfiguredBudgetField, number | undefined>>;
15
- type ConfiguredBudgetShape = Record<ConfiguredBudgetField, z.ZodOptional<ReturnType<typeof unlimitedInt>>>;
13
+ declare const timingFields: {
14
+ readonly modelTimeoutMs: "model_timeout_ms";
15
+ readonly streamIdleTimeoutMs: "stream_idle_timeout_ms";
16
+ readonly requestTotalTimeoutMs: "request_total_timeout_ms";
17
+ readonly toolTimeoutMs: "tool_timeout_ms";
18
+ readonly shellTimeoutMs: "shell_timeout_ms";
19
+ readonly maxParallelTools: "max_parallel_tools";
20
+ };
21
+ type ConfiguredBudgetField = (typeof budgetFields)[keyof typeof budgetFields];
22
+ type ConfiguredTimingField = (typeof timingFields)[keyof typeof timingFields];
23
+ type ConfiguredRunBudget = Partial<Record<ConfiguredBudgetField | ConfiguredTimingField, number | undefined>>;
16
24
  export declare function unlimitedInt(max?: number): z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>;
17
- export declare function configuredRunBudgetShape(maximums?: Required<ModeLimitsConfig>): ConfiguredBudgetShape;
25
+ export declare function configuredRunBudgetShape(maximums?: Required<RuntimeLimits>): {
26
+ model_timeout_ms: z.ZodOptional<z.ZodNumber>;
27
+ stream_idle_timeout_ms: z.ZodOptional<z.ZodNumber>;
28
+ request_total_timeout_ms: z.ZodOptional<z.ZodNumber>;
29
+ tool_timeout_ms: z.ZodOptional<z.ZodNumber>;
30
+ shell_timeout_ms: z.ZodOptional<z.ZodNumber>;
31
+ max_parallel_tools: z.ZodOptional<z.ZodNumber>;
32
+ max_model_attempts: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
33
+ max_tool_calls: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
34
+ max_steps: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
35
+ max_total_tokens: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
36
+ subagent_max_model_attempts: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
37
+ wall_time_ms: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
38
+ subagent_wall_time_ms: z.ZodOptional<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodLiteral<"unlimited">, z.ZodNull]>, z.ZodTransform<number, number | "unlimited" | null>>>;
39
+ };
18
40
  export interface ModeBudgetLayers {
19
41
  readonly defaults?: ModeLimitsConfig;
20
42
  readonly overrides?: ModeLimitsConfig;
21
43
  }
22
44
  export declare function readConfiguredRunBudget(raw: ConfiguredRunBudget | undefined): ModeLimitsConfig;
23
- export declare function resolveRunBudget(rawDefaults: ConfiguredRunBudget | undefined, modeBudget?: ModeBudgetLayers): Pick<RuntimeLimits, keyof ModeLimitsConfig>;
45
+ export declare function explicitTimingLimits(limits: Partial<RuntimeLimits> | undefined): Partial<RuntimeTimingLimits> | undefined;
46
+ export declare function resolveRunBudget(rawDefaults: ConfiguredRunBudget | undefined, modeBudget?: ModeBudgetLayers, explicitLimits?: Partial<RuntimeLimits>): RuntimeLimits;
24
47
  export {};
@@ -1,5 +1,21 @@
1
1
  import { DEFAULT_SUBAGENT_MAX_MODEL_ATTEMPTS, DEFAULT_SUBAGENT_WALL_TIME_MS, isLimited, } from '@saturn-universe/core';
2
+ import { maxPluginTimeoutMs, maxShellTimeoutMs } from '@saturn-universe/tools';
2
3
  import { z } from 'zod';
4
+ export const hardLimits = {
5
+ maxModelAttempts: 10000,
6
+ maxToolCalls: 10000,
7
+ maxSteps: 20000,
8
+ maxTotalTokens: 10000000,
9
+ subagentMaxModelAttempts: 10000,
10
+ wallTimeMs: 86400000,
11
+ subagentWallTimeMs: 86400000,
12
+ modelTimeoutMs: 600000,
13
+ streamIdleTimeoutMs: 600000,
14
+ requestTotalTimeoutMs: 600000,
15
+ toolTimeoutMs: maxPluginTimeoutMs,
16
+ shellTimeoutMs: maxShellTimeoutMs,
17
+ maxParallelTools: 64,
18
+ };
3
19
  const budgetFields = {
4
20
  maxModelAttempts: 'max_model_attempts',
5
21
  maxToolCalls: 'max_tool_calls',
@@ -9,7 +25,16 @@ const budgetFields = {
9
25
  wallTimeMs: 'wall_time_ms',
10
26
  subagentWallTimeMs: 'subagent_wall_time_ms',
11
27
  };
28
+ const timingFields = {
29
+ modelTimeoutMs: 'model_timeout_ms',
30
+ streamIdleTimeoutMs: 'stream_idle_timeout_ms',
31
+ requestTotalTimeoutMs: 'request_total_timeout_ms',
32
+ toolTimeoutMs: 'tool_timeout_ms',
33
+ shellTimeoutMs: 'shell_timeout_ms',
34
+ maxParallelTools: 'max_parallel_tools',
35
+ };
12
36
  const budgetKeys = Object.keys(budgetFields);
37
+ const timingKeys = Object.keys(timingFields);
13
38
  export function unlimitedInt(max) {
14
39
  const integer = z.number().int().min(0).safe();
15
40
  return z
@@ -17,24 +42,37 @@ export function unlimitedInt(max) {
17
42
  .transform((value) => (value === 'unlimited' || value === null ? 0 : value));
18
43
  }
19
44
  export function configuredRunBudgetShape(maximums) {
20
- return Object.fromEntries(budgetKeys.map((field) => [budgetFields[field], unlimitedInt(maximums?.[field]).optional()]));
45
+ const unlimitedFields = Object.fromEntries(budgetKeys.map((field) => [budgetFields[field], unlimitedInt(maximums?.[field]).optional()]));
46
+ const positive = z.number().int().positive().safe();
47
+ const timedFields = Object.fromEntries(timingKeys.map((field) => [timingFields[field], positive.max(hardLimits[field]).optional()]));
48
+ return { ...unlimitedFields, ...timedFields };
21
49
  }
22
50
  export function readConfiguredRunBudget(raw) {
51
+ const fields = { ...budgetFields, ...timingFields };
23
52
  const budget = {};
24
- for (const field of budgetKeys) {
25
- const value = raw?.[budgetFields[field]];
53
+ for (const field of [...budgetKeys, ...timingKeys]) {
54
+ const value = raw?.[fields[field]];
26
55
  if (value !== undefined)
27
56
  budget[field] = value;
28
57
  }
29
58
  return budget;
30
59
  }
31
- export function resolveRunBudget(rawDefaults, modeBudget) {
60
+ export function explicitTimingLimits(limits) {
61
+ const entries = timingKeys.flatMap((key) => {
62
+ const value = limits?.[key];
63
+ return value === undefined ? [] : [[key, value]];
64
+ });
65
+ return entries.length ? Object.fromEntries(entries) : undefined;
66
+ }
67
+ export function resolveRunBudget(rawDefaults, modeBudget, explicitLimits) {
32
68
  const budget = {
33
69
  ...modeBudget?.defaults,
34
70
  ...readConfiguredRunBudget(rawDefaults),
35
71
  ...modeBudget?.overrides,
72
+ ...explicitLimits,
36
73
  };
37
- const { wallTimeMs } = budget;
74
+ const { wallTimeMs, toolTimeoutMs, streamIdleTimeoutMs, requestTotalTimeoutMs } = budget;
75
+ const shellTimeoutMs = budget.shellTimeoutMs ?? (toolTimeoutMs === undefined ? maxShellTimeoutMs : undefined);
38
76
  return {
39
77
  maxModelAttempts: budget.maxModelAttempts ?? 0,
40
78
  maxToolCalls: budget.maxToolCalls ?? 0,
@@ -43,5 +81,11 @@ export function resolveRunBudget(rawDefaults, modeBudget) {
43
81
  subagentMaxModelAttempts: budget.subagentMaxModelAttempts ?? DEFAULT_SUBAGENT_MAX_MODEL_ATTEMPTS,
44
82
  ...(isLimited(wallTimeMs) ? { wallTimeMs } : {}),
45
83
  subagentWallTimeMs: budget.subagentWallTimeMs ?? DEFAULT_SUBAGENT_WALL_TIME_MS,
84
+ modelTimeoutMs: budget.modelTimeoutMs ?? 300000,
85
+ ...(streamIdleTimeoutMs !== undefined ? { streamIdleTimeoutMs } : {}),
86
+ ...(requestTotalTimeoutMs !== undefined ? { requestTotalTimeoutMs } : {}),
87
+ toolTimeoutMs: toolTimeoutMs ?? 30000,
88
+ ...(shellTimeoutMs !== undefined ? { shellTimeoutMs } : {}),
89
+ maxParallelTools: budget.maxParallelTools ?? 4,
46
90
  };
47
91
  }
@@ -0,0 +1,23 @@
1
+ import type { AutoCompactionOptions, RetryPolicy } from '@saturn-universe/core';
2
+ import { z } from 'zod';
3
+ export declare const modeRetrySchema: z.ZodObject<{
4
+ model_max_attempts_per_call: z.ZodOptional<z.ZodNumber>;
5
+ tool_max_attempts_per_call: z.ZodOptional<z.ZodNumber>;
6
+ base_delay_ms: z.ZodOptional<z.ZodNumber>;
7
+ max_delay_ms: z.ZodOptional<z.ZodNumber>;
8
+ }, z.core.$strict>;
9
+ export declare const modeCompactionSchema: z.ZodObject<{
10
+ enabled: z.ZodOptional<z.ZodBoolean>;
11
+ threshold_ratio: z.ZodOptional<z.ZodNumber>;
12
+ max_headroom_tokens: z.ZodOptional<z.ZodNumber>;
13
+ headroom_ratio: z.ZodOptional<z.ZodNumber>;
14
+ min_recent_steps: z.ZodOptional<z.ZodNumber>;
15
+ tail_window_ratio: z.ZodOptional<z.ZodNumber>;
16
+ preflight_window_ratio: z.ZodOptional<z.ZodNumber>;
17
+ max_halvings: z.ZodOptional<z.ZodNumber>;
18
+ min_prefix_chars: z.ZodOptional<z.ZodNumber>;
19
+ summary_timeout_ms: z.ZodOptional<z.ZodNumber>;
20
+ }, z.core.$strict>;
21
+ export declare function readModeRetry(raw: z.output<typeof modeRetrySchema>): Partial<RetryPolicy>;
22
+ export declare function resolveRetryPolicy(mode?: Partial<RetryPolicy>, explicit?: Partial<RetryPolicy>): RetryPolicy;
23
+ export declare function readModeCompaction(raw: z.output<typeof modeCompactionSchema>): AutoCompactionOptions;
@@ -0,0 +1,68 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ import { z } from 'zod';
3
+ const positive = z.number().int().positive().safe();
4
+ const nonnegative = z.number().int().nonnegative().safe();
5
+ const ratio = z.number().gt(0).lte(1);
6
+ const emptyRatio = z.number().gte(0).lte(1);
7
+ export const modeRetrySchema = z
8
+ .strictObject({
9
+ model_max_attempts_per_call: positive.optional(),
10
+ tool_max_attempts_per_call: positive.optional(),
11
+ base_delay_ms: positive.optional(),
12
+ max_delay_ms: positive.optional(),
13
+ })
14
+ .refine(({ base_delay_ms, max_delay_ms }) => base_delay_ms === undefined || max_delay_ms === undefined || base_delay_ms <= max_delay_ms);
15
+ export const modeCompactionSchema = z.strictObject({
16
+ enabled: z.boolean().optional(),
17
+ threshold_ratio: ratio.optional(),
18
+ max_headroom_tokens: nonnegative.optional(),
19
+ headroom_ratio: emptyRatio.optional(),
20
+ min_recent_steps: nonnegative.optional(),
21
+ tail_window_ratio: emptyRatio.optional(),
22
+ preflight_window_ratio: ratio.optional(),
23
+ max_halvings: nonnegative.optional(),
24
+ min_prefix_chars: nonnegative.optional(),
25
+ summary_timeout_ms: positive.optional(),
26
+ });
27
+ export function readModeRetry(raw) {
28
+ const { model_max_attempts_per_call, tool_max_attempts_per_call, base_delay_ms, max_delay_ms } = raw;
29
+ return {
30
+ ...(model_max_attempts_per_call !== undefined
31
+ ? { modelMaxAttemptsPerCall: model_max_attempts_per_call }
32
+ : {}),
33
+ ...(tool_max_attempts_per_call !== undefined
34
+ ? { toolMaxAttemptsPerCall: tool_max_attempts_per_call }
35
+ : {}),
36
+ ...(base_delay_ms !== undefined ? { baseDelayMs: base_delay_ms } : {}),
37
+ ...(max_delay_ms !== undefined ? { maxDelayMs: max_delay_ms } : {}),
38
+ };
39
+ }
40
+ export function resolveRetryPolicy(mode, explicit) {
41
+ const policy = {
42
+ modelMaxAttemptsPerCall: 3,
43
+ toolMaxAttemptsPerCall: 1,
44
+ baseDelayMs: 2000,
45
+ maxDelayMs: 5000,
46
+ ...mode,
47
+ ...explicit,
48
+ };
49
+ if (Object.values(policy).some((value) => !Number.isSafeInteger(value) || value < 1) ||
50
+ policy.baseDelayMs > policy.maxDelayMs) {
51
+ throw new RuntimeError('INVALID_CONFIG', 'Retry values must be positive integers and base delay must not exceed max delay');
52
+ }
53
+ return policy;
54
+ }
55
+ export function readModeCompaction(raw) {
56
+ return {
57
+ ...(raw.enabled !== undefined ? { enabled: raw.enabled } : {}),
58
+ ...(raw.threshold_ratio !== undefined ? { thresholdRatio: raw.threshold_ratio } : {}),
59
+ ...(raw.max_headroom_tokens !== undefined ? { maxHeadroomTokens: raw.max_headroom_tokens } : {}),
60
+ ...(raw.headroom_ratio !== undefined ? { headroomRatio: raw.headroom_ratio } : {}),
61
+ ...(raw.min_recent_steps !== undefined ? { minRecentSteps: raw.min_recent_steps } : {}),
62
+ ...(raw.tail_window_ratio !== undefined ? { tailWindowRatio: raw.tail_window_ratio } : {}),
63
+ ...(raw.preflight_window_ratio !== undefined ? { preflightWindowRatio: raw.preflight_window_ratio } : {}),
64
+ ...(raw.max_halvings !== undefined ? { maxHalvings: raw.max_halvings } : {}),
65
+ ...(raw.min_prefix_chars !== undefined ? { minPrefixChars: raw.min_prefix_chars } : {}),
66
+ ...(raw.summary_timeout_ms !== undefined ? { summaryTimeoutMs: raw.summary_timeout_ms } : {}),
67
+ };
68
+ }
@@ -4,6 +4,7 @@ export interface SandboxMetaRecord {
4
4
  readonly version: 1;
5
5
  readonly workspaceRoot: string;
6
6
  readonly workspaceHash: string;
7
+ readonly modeRef?: string;
7
8
  readonly sessionId?: string;
8
9
  readonly runId: string;
9
10
  readonly role: 'main' | 'worker' | 'target';
@@ -44,6 +45,7 @@ export interface SandboxManagerOptions {
44
45
  readonly allowUnsafeFallback?: boolean;
45
46
  readonly runner?: ContainerRunner;
46
47
  readonly checkKvmAvailable?: () => boolean;
48
+ readonly cleanupOrphans?: (cleanup: () => Promise<void>) => Promise<void>;
47
49
  }
48
50
  export interface SandboxTargetStartInput {
49
51
  readonly runId: RunId;
@@ -565,6 +565,10 @@ export function createSandboxManager(options) {
565
565
  for (const metaPath of metas) {
566
566
  try {
567
567
  const parsed = JSON.parse(await readFile(metaPath, 'utf8'));
568
+ if (parsed.modeRef ? parsed.modeRef !== mode.ref : !parsed.expiresAt) {
569
+ anyRunning = true;
570
+ break;
571
+ }
568
572
  hasMeta = true;
569
573
  if (parsed.status === 'running' ||
570
574
  (parsed.runId && runMemberSessions.get(parsed.runId)?.size)) {
@@ -712,6 +716,7 @@ export function createSandboxManager(options) {
712
716
  version: 1,
713
717
  workspaceRoot: root,
714
718
  workspaceHash,
719
+ modeRef: mode.ref,
715
720
  ...(effectiveSessionId !== undefined ? { sessionId: effectiveSessionId } : {}),
716
721
  runId: params.runId,
717
722
  role: params.role,
@@ -1055,18 +1060,18 @@ export function createSandboxManager(options) {
1055
1060
  return;
1056
1061
  }
1057
1062
  signal?.throwIfAborted();
1058
- const orphans = await runner
1059
- .listManagedContainers({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1060
- .catch(() => []);
1061
- for (const orphan of orphans) {
1062
- await runner.removeContainer(orphan.id).catch(() => { });
1063
- }
1064
- const orphanNetworks = await runner
1065
- .listManagedNetworks?.({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1066
- .catch(() => []);
1067
- for (const orphanNet of orphanNetworks ?? []) {
1068
- await runner.removeNetwork?.(orphanNet.name).catch(() => { });
1069
- }
1063
+ const cleanup = async () => {
1064
+ const labels = { 'saturn.managed': 'true', 'saturn.workspace': workspaceHash };
1065
+ const orphans = await runner.listManagedContainers(labels).catch(() => []);
1066
+ for (const orphan of orphans) {
1067
+ await runner.removeContainer(orphan.id).catch(() => { });
1068
+ }
1069
+ const orphanNetworks = await runner.listManagedNetworks?.(labels).catch(() => []);
1070
+ for (const orphanNet of orphanNetworks ?? []) {
1071
+ await runner.removeNetwork?.(orphanNet.name).catch(() => { });
1072
+ }
1073
+ };
1074
+ await (options.cleanupOrphans ? options.cleanupOrphans(cleanup) : cleanup());
1070
1075
  signal?.throwIfAborted();
1071
1076
  if (!resolvedImage || !(await runner.hasImage(resolvedImage))) {
1072
1077
  applyFallbackOrThrow('SANDBOX_IMAGE_MISSING', `Sandbox image "${resolvedImage ?? '(unspecified)'}" is missing locally`);
@@ -1364,6 +1369,7 @@ export function createSandboxManager(options) {
1364
1369
  version: 1,
1365
1370
  workspaceRoot: root,
1366
1371
  workspaceHash,
1372
+ modeRef: mode.ref,
1367
1373
  runId: input.runId,
1368
1374
  role: 'target',
1369
1375
  memberId: `target:${targetName}`,