@saturn-universe/runtime-host 0.0.0-stage → 0.1.1

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 (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +478 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +472 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,103 @@
1
+ import { RuntimeError, rewriteModelRequest, tightenToolPermission } from '@saturn-universe/core';
2
+ import { contributionScopeKey, globalScope, mainTarget, matchesScope, ScopedVersions, validateContributionScope, } from './scoped-layers.js';
3
+ import { registerPluginContribution, trackPluginWork } from './plugin-contributions.js';
4
+ export const runtimeHooksPlugin = {
5
+ name: 'runtime-hooks',
6
+ apply(ctx) {
7
+ const entries = new ScopedVersions('Hook', 'DUPLICATE_HOOK_BINDING');
8
+ let disposed = false;
9
+ ctx.effect(() => () => {
10
+ disposed = true;
11
+ entries.clear();
12
+ });
13
+ const service = {
14
+ register({ id, version }, hooks, { active = true, scope = globalScope } = {}) {
15
+ if (disposed)
16
+ throw new RuntimeError('HOST_DISPOSED', 'Runtime hooks are disposed');
17
+ if (!id.trim() || !version.trim())
18
+ throw new RuntimeError('INVALID_HOOK_BINDING', 'Hooks require an id and version');
19
+ const { beforeModelRequest, evaluateToolPermission, formatToolResult } = hooks;
20
+ if (!beforeModelRequest && !evaluateToolPermission && !formatToolResult)
21
+ throw new RuntimeError('INVALID_HOOK_BINDING', 'Register at least one Runtime hook');
22
+ const validated = validateContributionScope(scope);
23
+ const scopeKey = contributionScopeKey(validated);
24
+ const binding = { id, version, ...(scopeKey === undefined ? {} : { scopeKey }) };
25
+ return registerPluginContribution({ kind: 'hook', ...binding }, () => {
26
+ const registration = entries.register(binding, Object.freeze({
27
+ ...(beforeModelRequest && { beforeModelRequest: trackPluginWork(beforeModelRequest) }),
28
+ ...(evaluateToolPermission && {
29
+ evaluateToolPermission: trackPluginWork(evaluateToolPermission),
30
+ }),
31
+ ...(formatToolResult && { formatToolResult: trackPluginWork(formatToolResult) }),
32
+ }), validated, active);
33
+ return {
34
+ deactivate: registration,
35
+ activate: () => {
36
+ if (active)
37
+ registration.activate();
38
+ },
39
+ release: () => entries.release(binding),
40
+ };
41
+ });
42
+ },
43
+ list(target = mainTarget) {
44
+ return entries
45
+ .list(target)
46
+ .map((binding) => ({ ...binding }))
47
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
48
+ },
49
+ agentSessionIds: () => entries.agentSessionIds(),
50
+ resolve(binding) {
51
+ return entries.resolve(binding).value;
52
+ },
53
+ release(binding) {
54
+ return entries.release(binding);
55
+ },
56
+ forBindings(bindings, target = mainTarget) {
57
+ const hooks = bindings
58
+ .map((binding) => entries.resolve(binding))
59
+ .filter(({ scope }) => matchesScope(scope, target))
60
+ .map(({ value }) => value);
61
+ const rewrites = hooks.flatMap((hook) => (hook.beforeModelRequest ? [hook.beforeModelRequest] : []));
62
+ const permissions = hooks.flatMap((hook) => hook.evaluateToolPermission ? [hook.evaluateToolPermission] : []);
63
+ const formats = hooks.flatMap((hook) => (hook.formatToolResult ? [hook.formatToolResult] : []));
64
+ return {
65
+ ...(rewrites.length && {
66
+ async beforeModelRequest(request) {
67
+ let current = request;
68
+ for (const rewrite of rewrites)
69
+ current = await rewriteModelRequest(current, rewrite);
70
+ if (current !== request)
71
+ return { metadata: current.responsesOptions.metadata };
72
+ },
73
+ }),
74
+ ...(permissions.length && {
75
+ async evaluateToolPermission(request, permission) {
76
+ // Await each bound contribution. Cordis bail would stop at the first Promise.
77
+ for (const evaluate of permissions) {
78
+ const proposed = await evaluate(structuredClone(request), structuredClone(permission));
79
+ permission = tightenToolPermission(permission, proposed);
80
+ }
81
+ return permission;
82
+ },
83
+ }),
84
+ ...(formats.length && {
85
+ async formatToolResult(result, text) {
86
+ let replacement;
87
+ for (const format of formats) {
88
+ const proposed = await format(structuredClone(result), replacement ?? text);
89
+ if (proposed === undefined)
90
+ continue;
91
+ if (typeof proposed !== 'string')
92
+ throw new RuntimeError('INVALID_TOOL_RESULT_FORMAT', 'Tool result formatter must return text');
93
+ replacement = proposed;
94
+ }
95
+ return replacement;
96
+ },
97
+ }),
98
+ };
99
+ },
100
+ };
101
+ ctx.provide('saturnHooks', service);
102
+ },
103
+ };
@@ -0,0 +1,18 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ModeDefinition } from '@saturn-universe/core';
3
+ import type { ContainerRunner } from '@saturn-universe/tools';
4
+ import type { SandboxManager } from '../sandbox-manager.js';
5
+ declare module '@deepseek-ai/cordis' {
6
+ interface Context {
7
+ saturnSandbox?: SandboxManager;
8
+ }
9
+ }
10
+ export interface SandboxPluginOptions {
11
+ readonly allowUnsafeFallback?: boolean;
12
+ readonly runner?: ContainerRunner;
13
+ }
14
+ export declare function createSandboxPlugin(root: string, activeMode: ModeDefinition, options?: SandboxPluginOptions): {
15
+ name: string;
16
+ inject: string[];
17
+ apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
18
+ };
@@ -0,0 +1,21 @@
1
+ import { createSandboxManager } from '../sandbox-manager.js';
2
+ export function createSandboxPlugin(root, activeMode, options = {}) {
3
+ return {
4
+ name: 'sandbox',
5
+ inject: ['saturnPluginHost'],
6
+ async apply(ctx, startupSignal) {
7
+ const manager = createSandboxManager({
8
+ root,
9
+ mode: activeMode,
10
+ logger: ctx.saturnPluginHost.logger,
11
+ ...(options.allowUnsafeFallback ? { allowUnsafeFallback: true } : {}),
12
+ ...(options.runner ? { runner: options.runner } : {}),
13
+ });
14
+ await manager.activate(startupSignal);
15
+ ctx.effect(() => async () => {
16
+ await manager.dispose();
17
+ });
18
+ ctx.provide('saturnSandbox', manager);
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,63 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { AgentSessionId, ExecutionEnvironment, RunConfig } from '@saturn-universe/core';
3
+ declare const roles: readonly ["main", "worker", "planner", "search"];
4
+ export type AgentScopeRole = (typeof roles)[number];
5
+ export type ContributionScope = {
6
+ readonly kind: 'global';
7
+ } | {
8
+ readonly kind: 'role';
9
+ readonly roles: readonly AgentScopeRole[];
10
+ } | {
11
+ readonly kind: 'agentSession';
12
+ readonly agentSessionId: AgentSessionId;
13
+ };
14
+ export interface ContributionTarget {
15
+ readonly role: AgentScopeRole;
16
+ readonly agentSessionId?: AgentSessionId;
17
+ }
18
+ export declare const globalScope: {
19
+ readonly kind: "global";
20
+ };
21
+ export declare const mainTarget: {
22
+ readonly role: "main";
23
+ };
24
+ export declare function contributionScopeKey(scope: ContributionScope): string | undefined;
25
+ export declare function validateContributionScope(scope: unknown): ContributionScope;
26
+ export declare function matchesScope(scope: ContributionScope, target: ContributionTarget): boolean;
27
+ export declare function primaryRole(config: RunConfig): 'planner' | 'main';
28
+ export declare function executionTarget({ route: { agentSessionId }, config, membership, }: ExecutionEnvironment): ContributionTarget;
29
+ export declare class ScopedLayers<T> {
30
+ private readonly global;
31
+ private readonly byRole;
32
+ private readonly bySession;
33
+ register(scope: ContributionScope, key: string, value: T): () => void;
34
+ resolve({ role, agentSessionId }: ContributionTarget, include?: (value: T) => boolean): readonly T[];
35
+ agentSessionIds(): readonly AgentSessionId[];
36
+ }
37
+ type VersionBinding = {
38
+ readonly id: string;
39
+ readonly version: string;
40
+ readonly scopeKey?: string;
41
+ };
42
+ export declare class ScopedVersions<T> {
43
+ private readonly label;
44
+ private readonly conflictCode;
45
+ private readonly active;
46
+ private readonly retained;
47
+ constructor(label: string, conflictCode: string);
48
+ private key;
49
+ register({ id, version }: VersionBinding, value: T, scope: ContributionScope, active?: boolean): (() => void) & {
50
+ activate: () => void;
51
+ };
52
+ list(target: ContributionTarget): readonly VersionBinding[];
53
+ agentSessionIds(): readonly AgentSessionId[];
54
+ resolve(binding: VersionBinding): {
55
+ value: T;
56
+ scope: ContributionScope;
57
+ stop: () => void;
58
+ };
59
+ release(binding: VersionBinding): boolean;
60
+ clear(): void;
61
+ }
62
+ export declare function onScopedEvent<T>(ctx: Context, scope: ContributionScope, subscribe: (observe: (target: ContributionTarget, event: T) => void) => () => unknown, observe: (event: T, target: ContributionTarget) => void): import("@deepseek-ai/cordis").Disposable<Promise<void>>;
63
+ export {};
@@ -0,0 +1,170 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ const roles = ['main', 'worker', 'planner', 'search'];
3
+ export const globalScope = { kind: 'global' };
4
+ export const mainTarget = { role: 'main' };
5
+ export function contributionScopeKey(scope) {
6
+ if (scope.kind === 'global')
7
+ return undefined;
8
+ return scope.kind === 'role' ? `role:${scope.roles.join(',')}` : `session:${scope.agentSessionId}`;
9
+ }
10
+ export function validateContributionScope(scope) {
11
+ if (scope && typeof scope === 'object' && 'kind' in scope) {
12
+ if (scope.kind === 'global')
13
+ return globalScope;
14
+ if (scope.kind === 'role' && 'roles' in scope && Array.isArray(scope.roles)) {
15
+ const names = [...scope.roles];
16
+ if (names.length && names.every((name) => roles.some((role) => role === name)))
17
+ return { kind: 'role', roles: roles.filter((role) => names.includes(role)) };
18
+ }
19
+ if (scope.kind === 'agentSession' &&
20
+ 'agentSessionId' in scope &&
21
+ typeof scope.agentSessionId === 'string' &&
22
+ scope.agentSessionId.trim())
23
+ return { kind: 'agentSession', agentSessionId: scope.agentSessionId };
24
+ }
25
+ throw new RuntimeError('INVALID_CONTRIBUTION_SCOPE', 'Expected global, nonempty valid roles, or an Agent session ID');
26
+ }
27
+ export function matchesScope(scope, target) {
28
+ switch (scope.kind) {
29
+ case 'global':
30
+ return true;
31
+ case 'role':
32
+ return scope.roles.includes(target.role);
33
+ case 'agentSession':
34
+ return scope.agentSessionId === target.agentSessionId;
35
+ }
36
+ }
37
+ export function primaryRole(config) {
38
+ return config.toolSetVersion === 'planner' || config.modeRef === 'planner@1' ? 'planner' : 'main';
39
+ }
40
+ export function executionTarget({ route: { agentSessionId }, config, membership, }) {
41
+ if (membership?.searchBranchId !== undefined)
42
+ return { role: 'search', agentSessionId };
43
+ if (membership?.role === 'worker')
44
+ return { role: membership.teamMemberId === undefined ? 'planner' : 'worker', agentSessionId };
45
+ return { role: primaryRole(config), agentSessionId };
46
+ }
47
+ function layer(layers, id) {
48
+ const existing = layers.get(id);
49
+ if (existing)
50
+ return existing;
51
+ const created = new Map();
52
+ layers.set(id, created);
53
+ return created;
54
+ }
55
+ export class ScopedLayers {
56
+ global = new Map();
57
+ byRole = new Map();
58
+ bySession = new Map();
59
+ register(scope, key, value) {
60
+ const validated = validateContributionScope(scope);
61
+ const layers = validated.kind === 'global'
62
+ ? [this.global]
63
+ : validated.kind === 'role'
64
+ ? validated.roles.map((role) => layer(this.byRole, role))
65
+ : [layer(this.bySession, validated.agentSessionId)];
66
+ if (layers.some((entries) => entries.has(key)))
67
+ throw new RuntimeError('DUPLICATE_SCOPED_CONTRIBUTION', `Contribution ${key} already exists in this scope`);
68
+ for (const entries of layers)
69
+ entries.set(key, value);
70
+ let active = true;
71
+ return () => {
72
+ if (!active)
73
+ return;
74
+ active = false;
75
+ for (const entries of layers)
76
+ entries.delete(key);
77
+ if (validated.kind === 'agentSession' && !layers[0].size)
78
+ this.bySession.delete(validated.agentSessionId);
79
+ };
80
+ }
81
+ resolve({ role, agentSessionId }, include = () => true) {
82
+ const result = new Map();
83
+ const session = agentSessionId === undefined ? undefined : this.bySession.get(agentSessionId);
84
+ for (const entries of [this.global, this.byRole.get(role), session]) {
85
+ if (!entries)
86
+ continue;
87
+ for (const key of [...entries.keys()].sort()) {
88
+ const value = entries.get(key);
89
+ if (include(value))
90
+ result.set(key, value);
91
+ }
92
+ }
93
+ return [...result.values()];
94
+ }
95
+ agentSessionIds() {
96
+ return [...this.bySession.keys()].sort();
97
+ }
98
+ }
99
+ export class ScopedVersions {
100
+ label;
101
+ conflictCode;
102
+ active = new ScopedLayers();
103
+ retained = new Map();
104
+ constructor(label, conflictCode) {
105
+ this.label = label;
106
+ this.conflictCode = conflictCode;
107
+ }
108
+ key({ id, version, scopeKey }) {
109
+ return JSON.stringify([id, version, scopeKey]);
110
+ }
111
+ register({ id, version }, value, scope, active = true) {
112
+ const validated = validateContributionScope(scope);
113
+ const scopeKey = contributionScopeKey(validated);
114
+ const binding = { id, version, ...(scopeKey === undefined ? {} : { scopeKey }) };
115
+ const key = this.key(binding);
116
+ const conflict = () => new RuntimeError(this.conflictCode, `${this.label} ${id}@${version} conflicts with a registration`);
117
+ if (this.retained.has(key))
118
+ throw conflict();
119
+ let stop;
120
+ const activate = () => {
121
+ if (stop)
122
+ return;
123
+ try {
124
+ stop = this.active.register(validated, id, binding);
125
+ }
126
+ catch (error) {
127
+ if (error instanceof RuntimeError && error.code === 'DUPLICATE_SCOPED_CONTRIBUTION')
128
+ throw conflict();
129
+ throw error;
130
+ }
131
+ };
132
+ const deactivate = () => {
133
+ stop?.();
134
+ stop = undefined;
135
+ };
136
+ if (active)
137
+ activate();
138
+ this.retained.set(key, { value, scope: validated, stop: deactivate });
139
+ return Object.assign(deactivate, { activate });
140
+ }
141
+ list(target) {
142
+ return this.active.resolve(target);
143
+ }
144
+ agentSessionIds() {
145
+ return this.active.agentSessionIds();
146
+ }
147
+ resolve(binding) {
148
+ const entry = this.retained.get(this.key(binding));
149
+ if (!entry)
150
+ throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `${this.label} ${binding.id}@${binding.version} is unavailable`);
151
+ return entry;
152
+ }
153
+ release(binding) {
154
+ const key = this.key(binding);
155
+ this.retained.get(key)?.stop();
156
+ return this.retained.delete(key);
157
+ }
158
+ clear() {
159
+ for (const entry of this.retained.values())
160
+ entry.stop();
161
+ this.retained.clear();
162
+ }
163
+ }
164
+ export function onScopedEvent(ctx, scope, subscribe, observe) {
165
+ const validated = validateContributionScope(scope);
166
+ return ctx.effect(() => subscribe((target, event) => {
167
+ if (matchesScope(validated, target))
168
+ observe(event, target);
169
+ }));
170
+ }
@@ -0,0 +1,11 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { PromptSection, RunConfig, RunId, ToolBinding, ToolSpec } from '@saturn-universe/core';
3
+ import { type TeamNotifyParentDelivery } from '@saturn-universe/tools';
4
+ import type { ToolConfiguration } from './tools-core-plugin.js';
5
+ import { type SkillRegistryService } from '../../skills-runtime.js';
6
+ export declare function teamHintSections(hint: RunConfig['teamHint'], tools: readonly ToolSpec[]): PromptSection[];
7
+ export declare function createBuiltinAgentToolsPlugin(root: string, settings: ToolConfiguration['counter'], resultReader?: ToolBinding, previousDataReview?: (runId: RunId) => Promise<boolean>, suppressedGuidanceRoles?: ReadonlySet<'main' | 'worker'>, skillService?: SkillRegistryService, notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>): {
8
+ name: string;
9
+ inject: string[];
10
+ apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
11
+ };
@@ -0,0 +1,171 @@
1
+ import path from 'node:path';
2
+ import { buildTeamHintPrompt } from '@saturn-universe/context';
3
+ import { createCounterTool, createDataReviewTool, createPlannerTool, createSpawnTeamTool, createTeamNotifyParentTool, createTodoWriteTool, dataReviewToolSet, teamNotifyParentToolName, } from '@saturn-universe/tools';
4
+ import { sharedToolPriority } from './tools-core-plugin.js';
5
+ import { registerToolGuidance } from './tool-guidance.js';
6
+ import { createNativeSkillTool, skillToolName } from '../../skills-runtime.js';
7
+ // The built-in tools provider carries this Run hint for both current and historical bindings.
8
+ export function teamHintSections(hint, tools) {
9
+ if (!hint || !tools.some(({ canonicalName }) => canonicalName === 'spawn_team'))
10
+ return [];
11
+ return [
12
+ {
13
+ id: 'team-hint',
14
+ source: 'tools',
15
+ priority: 85,
16
+ authority: 'configured_instruction',
17
+ required: false,
18
+ text: buildTeamHintPrompt(hint),
19
+ },
20
+ ];
21
+ }
22
+ export function createBuiltinAgentToolsPlugin(root, settings, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent) {
23
+ return {
24
+ name: 'builtin-agent-tools',
25
+ inject: ['saturnTools'],
26
+ async apply(ctx, startupSignal) {
27
+ const tools = ctx.saturnTools;
28
+ const counter = settings &&
29
+ createCounterTool(path.join(root, '.saturn', 'counter'), {
30
+ reconcile: settings.reconcile ?? false,
31
+ holdAfterApply: settings.holdAfterApply ?? false,
32
+ });
33
+ const sets = await tools.setAgentDefinitions(counter?.definition, resultReader?.definition);
34
+ startupSignal.throwIfAborted();
35
+ if (counter)
36
+ ctx.effect(() => tools.registry.register(counter.definition, counter.handler, sets.counterVersions, {
37
+ order: { tier: 'shared', priority: sharedToolPriority.counter },
38
+ }));
39
+ if (resultReader)
40
+ ctx.effect(() => tools.registry.register(resultReader.definition, resultReader.handler, sets.readerVersions, {
41
+ order: { tier: 'shared', priority: sharedToolPriority.resultReader },
42
+ }));
43
+ const store = ctx.get('saturnStorage')?.store;
44
+ const resolveCaller = store
45
+ ? async (toolCtx) => {
46
+ try {
47
+ const env = await store.environmentReader.load(toolCtx.runId, toolCtx.agentSessionId);
48
+ const memberId = env.membership?.teamMemberId ?? 'main';
49
+ const depth = env.config.agentDepth ?? (env.membership?.role === 'worker' ? 1 : 0);
50
+ const maxDepth = env.config.teamMaxDepth ?? 1;
51
+ let activeDepth1Count = 0;
52
+ if (depth === 0 && env.config.teamMaxActiveDepth1 !== undefined) {
53
+ const team = await store.stateReader.team?.(toolCtx.runId);
54
+ activeDepth1Count = (team?.members ?? []).filter((member) => member.parent === 'main' &&
55
+ !['completed', 'failed', 'interrupted'].includes(member.status)).length;
56
+ }
57
+ return {
58
+ memberId,
59
+ depth,
60
+ maxDepth,
61
+ modeRef: env.config.modeRef,
62
+ ...(env.config.teamMaxActiveDepth1 !== undefined
63
+ ? { maxActiveDepth1: env.config.teamMaxActiveDepth1 }
64
+ : {}),
65
+ ...(depth === 0 ? { activeDepth1Count } : {}),
66
+ ...(env.config.teamMaxConcurrency !== undefined
67
+ ? { maxConcurrentWorkers: env.config.teamMaxConcurrency }
68
+ : {}),
69
+ };
70
+ }
71
+ catch {
72
+ return { memberId: 'main', depth: 0, maxDepth: 1 };
73
+ }
74
+ }
75
+ : undefined;
76
+ const spawnTeamV1Versions = sets.defaultVersions.filter((version) => !sets.spawnTeamV2Versions.includes(version));
77
+ const tail = [
78
+ // Existing Run bindings can still resolve v1 even when no historical set is configured.
79
+ {
80
+ binding: createSpawnTeamTool({ ...(resolveCaller ? { resolveCaller } : {}) }),
81
+ versions: spawnTeamV1Versions,
82
+ priority: 0,
83
+ },
84
+ {
85
+ binding: createSpawnTeamTool({
86
+ includeSandboxProfile: true,
87
+ includeWorkSubpath: true,
88
+ ...(resolveCaller ? { resolveCaller } : {}),
89
+ }),
90
+ versions: sets.spawnTeamV2Versions,
91
+ priority: 0,
92
+ },
93
+ {
94
+ binding: createTodoWriteTool(),
95
+ versions: [...sets.defaultVersions, dataReviewToolSet],
96
+ priority: 1,
97
+ },
98
+ { binding: createPlannerTool(), versions: ['planner'], priority: 2 },
99
+ { binding: createDataReviewTool(previousDataReview), versions: [dataReviewToolSet], priority: 3 },
100
+ ...(skillService && skillService.skills.length > 0
101
+ ? [{ binding: createNativeSkillTool(skillService), versions: sets.defaultVersions, priority: 4 }]
102
+ : []),
103
+ ];
104
+ for (const { binding: { definition, handler }, versions, priority, } of tail)
105
+ ctx.effect(() => tools.registry.register(definition, handler, versions, { order: { tier: 'tail', priority } }));
106
+ const resolveNotifyCaller = store
107
+ ? async (toolCtx) => {
108
+ try {
109
+ const env = await store.environmentReader.load(toolCtx.runId, toolCtx.agentSessionId);
110
+ const memberId = env.membership?.teamMemberId ?? 'main';
111
+ const depth = env.config.agentDepth ?? (env.membership?.role === 'worker' ? 1 : 0);
112
+ const team = await store.stateReader.team?.(toolCtx.runId);
113
+ const member = team?.members.find((item) => item.id === memberId);
114
+ const parentId = member?.parent ?? (memberId !== 'main' ? 'main' : null);
115
+ return { memberId, parentId, depth };
116
+ }
117
+ catch {
118
+ return { memberId: 'main', parentId: null, depth: 0 };
119
+ }
120
+ }
121
+ : undefined;
122
+ const notifyParentTool = createTeamNotifyParentTool({
123
+ ...(resolveNotifyCaller ? { resolveCaller: resolveNotifyCaller } : {}),
124
+ ...(notifyParent ? { notifyParent } : {}),
125
+ });
126
+ ctx.effect(() => tools.registerTool(notifyParentTool.definition, notifyParentTool.handler, sets.defaultVersions, {
127
+ scope: { kind: 'role', roles: ['worker'] },
128
+ order: { tier: 'tail', priority: 5 },
129
+ }));
130
+ registerToolGuidance(ctx, 'agent-tool-guidance', -30, (visible, config) => {
131
+ const lines = [];
132
+ if (visible.has('read_tool_result'))
133
+ lines.push('Truncated results: Use read_tool_result with the actual tool_call_id to retrieve missing output. Never guess what was omitted.');
134
+ if (visible.has('todo_write'))
135
+ lines.push('Task tracking: Skip todo_write for simple single-step tasks. For multi-step tasks, maintain and update concise milestones. Mark a core objective completed only when fully done, and cancelled only at the user’s request or for a tool-verified external blocker.');
136
+ if (visible.has(skillToolName) &&
137
+ (!skillService || skillService.indexSkills(config.disabledSkills).length > 0))
138
+ lines.push('Agent skills: Before executing a specialized task that matches an entry in <available_skills>, you MUST call `skill(action="load", skill="<name>")` once upfront (batchable with initial read-only inspection) to load full methodology, and call `skill(action="read_resource", ...)` for sibling references or scripts as needed. Do not reload an already-loaded skill in the same session.');
139
+ return lines.join('\n');
140
+ });
141
+ if (!suppressedGuidanceRoles?.has('main')) {
142
+ registerToolGuidance(ctx, 'team-guidance', -40, (visible, config) => {
143
+ if (!visible.has('spawn_team'))
144
+ return '';
145
+ return [
146
+ config.teamHint
147
+ ? 'Team delegation: Follow the team mode hint.'
148
+ : 'Team delegation: Default to executing single-file, single-binary, simple linear verification, or short-command tasks directly yourself—do not spawn workers for simple static checks, single debugging sessions, or short validation scripts. Use spawn_team only when the task genuinely involves two or more time-consuming, independent modules or subsystems (such as separate services, frontend/backend splits, or large multi-module codebases) that require parallel work while you are occupied.',
149
+ 'Assign non-overlapping scopes and specific deliverables. End the current Turn immediately after calling spawn_team with no further tool calls.',
150
+ 'Critically synthesize worker reports. Verify disputed findings empirically and reuse verified checks already performed.',
151
+ ].join(' ');
152
+ }, { kind: 'role', roles: ['main'] });
153
+ }
154
+ if (!suppressedGuidanceRoles?.has('worker')) {
155
+ registerToolGuidance(ctx, 'team-guidance', -40, (visible) => [
156
+ 'Worker scope: Stay within your assignment and avoid duplicating teammates’ work. Report concise, empirically verified facts with exact paths, symbols, command observations, and follow-up leads.',
157
+ ...(visible.has('spawn_team')
158
+ ? [
159
+ 'Sub-team delegation: You may call spawn_team (parent can be omitted to default to your own member ID) to delegate leaf sub-tasks when parallel sub-work is justified, then end your turn immediately with no further tool calls.',
160
+ ]
161
+ : []),
162
+ ...(visible.has(teamNotifyParentToolName)
163
+ ? [
164
+ 'Incremental parent updates: Use `team_notify_parent({ message, kind? })` to push milestones, quota/cooldown blocks, or cross-task clues to `main` without interrupting your current turn.',
165
+ ]
166
+ : []),
167
+ ].join(' '), { kind: 'role', roles: ['worker'] });
168
+ }
169
+ },
170
+ };
171
+ }
@@ -0,0 +1,17 @@
1
+ import type { RunId, ToolBinding } from '@saturn-universe/core';
2
+ import type { ProcessManagerOptions, TeamNotifyParentDelivery } from '@saturn-universe/tools';
3
+ import type { SkillRegistryService } from '../../skills-runtime.js';
4
+ import type { RequiredHostPlugin } from '../required-host-plugin.js';
5
+ import type { ToolConfiguration } from './tools-core-plugin.js';
6
+ export interface HostToolOptions {
7
+ config: ToolConfiguration;
8
+ trustedConfig: boolean;
9
+ hash: (value: unknown) => string;
10
+ resultReader?: ToolBinding;
11
+ processManager?: Omit<ProcessManagerOptions, 'directory'>;
12
+ previousDataReview?: (runId: RunId) => Promise<boolean>;
13
+ suppressedGuidanceRoles?: ReadonlySet<'main' | 'worker'>;
14
+ skillService?: SkillRegistryService;
15
+ notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>;
16
+ }
17
+ export declare function createToolPlugins(root: string, options: HostToolOptions, startupDependencies?: string[], withContext?: boolean): RequiredHostPlugin[];
@@ -0,0 +1,40 @@
1
+ import { createBuiltinAgentToolsPlugin } from './builtin-agent-tools-plugin.js';
2
+ import { createMcpToolsPlugin } from './mcp-tools-plugin.js';
3
+ import { createProcessManagerPlugin } from './process-manager-plugin.js';
4
+ import { createToolsCorePlugin } from './tools-core-plugin.js';
5
+ import { createWorkspaceToolsPlugin } from './workspace-tools-plugin.js';
6
+ export function createToolPlugins(root, options, startupDependencies = [], withContext = false) {
7
+ const { config, trustedConfig, hash, resultReader, processManager, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, } = options;
8
+ const effectiveWorkspaceTools = Boolean(config.workspaceTools);
9
+ const effectiveProcessManager = config.processManager ?? effectiveWorkspaceTools;
10
+ const effectiveBuiltinAgentTools = config.builtinAgentTools !== false;
11
+ const guidanceOwner = (plugin, dependencies = []) => withContext
12
+ ? { ...plugin, inject: [...(plugin.inject ?? []), 'saturnContext', ...dependencies] }
13
+ : plugin;
14
+ return [
15
+ { ...createToolsCorePlugin(config, trustedConfig, hash), inject: startupDependencies },
16
+ ...(effectiveProcessManager
17
+ ? [
18
+ guidanceOwner({
19
+ ...createProcessManagerPlugin(root, processManager ?? {}),
20
+ inject: [...startupDependencies, 'saturnTools'],
21
+ }),
22
+ ]
23
+ : []),
24
+ ...(effectiveWorkspaceTools
25
+ ? [
26
+ guidanceOwner(createWorkspaceToolsPlugin(root, { withProcessManager: effectiveProcessManager }), [
27
+ 'saturnEnvProbe',
28
+ ]),
29
+ ]
30
+ : []),
31
+ ...(effectiveBuiltinAgentTools
32
+ ? [
33
+ guidanceOwner(createBuiltinAgentToolsPlugin(root, config.counter, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent)),
34
+ ]
35
+ : []),
36
+ ...(Object.keys(config.mcpServers ?? {}).length
37
+ ? [createMcpToolsPlugin(root, config, trustedConfig)]
38
+ : []),
39
+ ];
40
+ }
@@ -0,0 +1,7 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ToolConfiguration } from './tools-core-plugin.js';
3
+ export declare function createMcpToolsPlugin(root: string, config: ToolConfiguration, trustedConfig: boolean): {
4
+ name: string;
5
+ inject: string[];
6
+ apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
7
+ };