@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.
- package/LICENSE +661 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
- package/dist/command-dispatch.d.ts +10 -0
- package/dist/command-dispatch.js +65 -0
- package/dist/completion-judge.d.ts +10 -0
- package/dist/completion-judge.js +156 -0
- package/dist/composition.d.ts +108 -0
- package/dist/composition.js +1180 -0
- package/dist/configuration.d.ts +49 -0
- package/dist/configuration.js +51 -0
- package/dist/context-extensions.d.ts +681 -0
- package/dist/context-extensions.js +289 -0
- package/dist/cordis/context-core-plugin.d.ts +35 -0
- package/dist/cordis/context-core-plugin.js +296 -0
- package/dist/cordis/env-probe-plugin.d.ts +27 -0
- package/dist/cordis/env-probe-plugin.js +114 -0
- package/dist/cordis/host-context.d.ts +65 -0
- package/dist/cordis/host-context.js +199 -0
- package/dist/cordis/model-responses-plugin.d.ts +81 -0
- package/dist/cordis/model-responses-plugin.js +209 -0
- package/dist/cordis/plugin-contributions.d.ts +47 -0
- package/dist/cordis/plugin-contributions.js +119 -0
- package/dist/cordis/plugin-lifecycle.d.ts +57 -0
- package/dist/cordis/plugin-lifecycle.js +222 -0
- package/dist/cordis/plugin-loader.d.ts +18 -0
- package/dist/cordis/plugin-loader.js +310 -0
- package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
- package/dist/cordis/plugin-sdk-adapter.js +283 -0
- package/dist/cordis/required-host-plugin.d.ts +6 -0
- package/dist/cordis/required-host-plugin.js +1 -0
- package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
- package/dist/cordis/runtime-hooks-plugin.js +103 -0
- package/dist/cordis/sandbox-plugin.d.ts +18 -0
- package/dist/cordis/sandbox-plugin.js +21 -0
- package/dist/cordis/scoped-layers.d.ts +63 -0
- package/dist/cordis/scoped-layers.js +170 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
- package/dist/cordis/tools/index.d.ts +17 -0
- package/dist/cordis/tools/index.js +40 -0
- package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
- package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
- package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
- package/dist/cordis/tools/process-manager-plugin.js +39 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
- package/dist/cordis/tools/tool-guidance.d.ts +4 -0
- package/dist/cordis/tools/tool-guidance.js +30 -0
- package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
- package/dist/cordis/tools/tools-core-plugin.js +486 -0
- package/dist/cordis/tools/web-fetch.d.ts +17 -0
- package/dist/cordis/tools/web-fetch.js +529 -0
- package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
- package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
- package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
- package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
- package/dist/env-probe.d.ts +8 -0
- package/dist/env-probe.js +172 -0
- package/dist/host-configuration.d.ts +27 -0
- package/dist/host-configuration.js +185 -0
- package/dist/host-tools.d.ts +19 -0
- package/dist/host-tools.js +30 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +140 -0
- package/dist/ipc.d.ts +24 -0
- package/dist/ipc.js +162 -0
- package/dist/logger.d.ts +11 -0
- package/dist/logger.js +84 -0
- package/dist/mcp-configuration.d.ts +17 -0
- package/dist/mcp-configuration.js +50 -0
- package/dist/modes.d.ts +27 -0
- package/dist/modes.js +478 -0
- package/dist/ownership.d.ts +7 -0
- package/dist/ownership.js +100 -0
- package/dist/plugin-configuration.d.ts +9 -0
- package/dist/plugin-configuration.js +21 -0
- package/dist/plugin-tool-grants.d.ts +18 -0
- package/dist/plugin-tool-grants.js +21 -0
- package/dist/process-workspaces.d.ts +4 -0
- package/dist/process-workspaces.js +28 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +699 -0
- package/dist/provider-catalog.d.ts +754 -0
- package/dist/provider-catalog.js +472 -0
- package/dist/run-budget.d.ts +24 -0
- package/dist/run-budget.js +47 -0
- package/dist/run-checkpoint.d.ts +2 -0
- package/dist/run-checkpoint.js +52 -0
- package/dist/sandbox-manager.d.ts +111 -0
- package/dist/sandbox-manager.js +1519 -0
- package/dist/session-paths.d.ts +15 -0
- package/dist/session-paths.js +40 -0
- package/dist/side-question.d.ts +14 -0
- package/dist/side-question.js +89 -0
- package/dist/skills-runtime.d.ts +13 -0
- package/dist/skills-runtime.js +243 -0
- package/dist/token-estimator.d.ts +3 -0
- package/dist/token-estimator.js +73 -0
- package/dist/tool-result.d.ts +2 -0
- package/dist/tool-result.js +91 -0
- package/dist/user-config.d.ts +23 -0
- package/dist/user-config.js +36 -0
- package/package.json +28 -3
- package/README.md +0 -3
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
4
|
+
import { normalizeWorkspaceTrustPath, parseProjectMcpJson, projectMcpConfigPath, userConfigPath, workspaceConfigPath, } from '@saturn-universe/protocol';
|
|
5
|
+
import { parseProviderToml } from './provider-catalog.js';
|
|
6
|
+
export function parseHostArguments(args) {
|
|
7
|
+
let root;
|
|
8
|
+
let configFile;
|
|
9
|
+
let profile;
|
|
10
|
+
let taskProfile;
|
|
11
|
+
let mode;
|
|
12
|
+
let allowUnsafeSandboxFallback = false;
|
|
13
|
+
for (let i = 0; i < args.length; i++) {
|
|
14
|
+
const arg = args[i];
|
|
15
|
+
if (arg === '--allow-unsafe-sandbox-fallback') {
|
|
16
|
+
allowUnsafeSandboxFallback = true;
|
|
17
|
+
}
|
|
18
|
+
else if (['--config', '--profile', '--task-profile', '--mode'].includes(arg)) {
|
|
19
|
+
const value = args[++i];
|
|
20
|
+
if (!value || value.startsWith('--'))
|
|
21
|
+
throw invalid();
|
|
22
|
+
if (arg === '--config') {
|
|
23
|
+
if (configFile)
|
|
24
|
+
throw invalid();
|
|
25
|
+
configFile = value;
|
|
26
|
+
}
|
|
27
|
+
if (arg === '--profile') {
|
|
28
|
+
if (profile)
|
|
29
|
+
throw invalid();
|
|
30
|
+
profile = value;
|
|
31
|
+
}
|
|
32
|
+
if (arg === '--task-profile') {
|
|
33
|
+
if (taskProfile)
|
|
34
|
+
throw invalid();
|
|
35
|
+
taskProfile = value;
|
|
36
|
+
}
|
|
37
|
+
if (arg === '--mode') {
|
|
38
|
+
if (mode)
|
|
39
|
+
throw invalid();
|
|
40
|
+
mode = value;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else if (arg.startsWith('--'))
|
|
44
|
+
throw invalid();
|
|
45
|
+
else if (!root)
|
|
46
|
+
root = arg;
|
|
47
|
+
else
|
|
48
|
+
throw invalid();
|
|
49
|
+
}
|
|
50
|
+
if (!root)
|
|
51
|
+
root = process.cwd();
|
|
52
|
+
return {
|
|
53
|
+
root,
|
|
54
|
+
...(configFile ? { configFile } : {}),
|
|
55
|
+
...(profile ? { profile } : {}),
|
|
56
|
+
...(taskProfile ? { taskProfile } : {}),
|
|
57
|
+
...(mode ? { mode } : {}),
|
|
58
|
+
...(allowUnsafeSandboxFallback ? { allowUnsafeSandboxFallback: true } : {}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
async function readOptionalUserCatalog(env) {
|
|
62
|
+
try {
|
|
63
|
+
const text = await readFile(userConfigPath(env), 'utf8');
|
|
64
|
+
return parseProviderToml(text);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async function readOptionalProjectMcpJson(filename) {
|
|
71
|
+
let text;
|
|
72
|
+
try {
|
|
73
|
+
text = await readFile(filename, 'utf8');
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
if (error.code === 'ENOENT')
|
|
77
|
+
return {};
|
|
78
|
+
return { error: 'Could not read .mcp.json' };
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
return { servers: parseProjectMcpJson(text) };
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
return { error: error instanceof Error ? error.message : 'Invalid .mcp.json' };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
export async function loadHostConfiguration(root, explicitFile, env = process.env) {
|
|
88
|
+
if (explicitFile && path.extname(explicitFile).toLowerCase() !== '.toml')
|
|
89
|
+
throw invalid();
|
|
90
|
+
const candidates = [
|
|
91
|
+
...(explicitFile ? [{ filename: explicitFile, optional: false, source: 'explicit' }] : []),
|
|
92
|
+
{
|
|
93
|
+
filename: workspaceConfigPath(root),
|
|
94
|
+
optional: true,
|
|
95
|
+
source: 'workspace',
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
filename: userConfigPath(env),
|
|
99
|
+
optional: true,
|
|
100
|
+
source: 'user',
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
let resolvedCatalog;
|
|
104
|
+
let configSource = 'none';
|
|
105
|
+
let configPath;
|
|
106
|
+
let trusted = false;
|
|
107
|
+
for (const candidate of candidates) {
|
|
108
|
+
const { optional, source } = candidate;
|
|
109
|
+
const filename = path.resolve(candidate.filename);
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = await readFile(filename, 'utf8');
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (optional && error.code === 'ENOENT')
|
|
116
|
+
continue;
|
|
117
|
+
throw invalid();
|
|
118
|
+
}
|
|
119
|
+
trusted = source === 'user' || source === 'explicit';
|
|
120
|
+
configSource = source;
|
|
121
|
+
configPath = filename;
|
|
122
|
+
resolvedCatalog = parseProviderToml(text);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
const userCatalog = configSource === 'user' ? resolvedCatalog : await readOptionalUserCatalog(env);
|
|
126
|
+
const trustedWorkspaces = new Set((userCatalog?.trustedMcpWorkspaces ?? []).map((entry) => normalizeWorkspaceTrustPath(entry)));
|
|
127
|
+
const workspaceTrustedForMcp = trustedWorkspaces.has(normalizeWorkspaceTrustPath(root));
|
|
128
|
+
const mcpJsonPath = projectMcpConfigPath(root);
|
|
129
|
+
const projectMcp = await readOptionalProjectMcpJson(mcpJsonPath);
|
|
130
|
+
const mergedMcpServers = {};
|
|
131
|
+
const mcpServerMeta = {};
|
|
132
|
+
const primaryMcpServers = resolvedCatalog?.mcpServers;
|
|
133
|
+
if (primaryMcpServers && configSource !== 'none') {
|
|
134
|
+
for (const [id, server] of Object.entries(primaryMcpServers)) {
|
|
135
|
+
mergedMcpServers[id] = server;
|
|
136
|
+
mcpServerMeta[id] = {
|
|
137
|
+
scope: configSource,
|
|
138
|
+
source: configPath ?? configSource,
|
|
139
|
+
trusted,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if ((configSource === 'workspace' || configSource === 'none') && userCatalog?.mcpServers) {
|
|
144
|
+
const userPath = userConfigPath(env);
|
|
145
|
+
for (const [id, server] of Object.entries(userCatalog.mcpServers)) {
|
|
146
|
+
if (Object.hasOwn(mergedMcpServers, id))
|
|
147
|
+
continue;
|
|
148
|
+
mergedMcpServers[id] = server;
|
|
149
|
+
mcpServerMeta[id] = {
|
|
150
|
+
scope: 'user',
|
|
151
|
+
source: userPath,
|
|
152
|
+
trusted: true,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (projectMcp.servers) {
|
|
157
|
+
for (const [id, server] of Object.entries(projectMcp.servers)) {
|
|
158
|
+
if (Object.hasOwn(mergedMcpServers, id))
|
|
159
|
+
continue;
|
|
160
|
+
mergedMcpServers[id] = server;
|
|
161
|
+
mcpServerMeta[id] = {
|
|
162
|
+
scope: 'project',
|
|
163
|
+
source: mcpJsonPath,
|
|
164
|
+
trusted: workspaceTrustedForMcp,
|
|
165
|
+
fromProjectMcpJson: true,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const hasMergedMcp = Object.keys(mergedMcpServers).length > 0;
|
|
170
|
+
// A workspace-controlled TOML cannot select which Host secret to send to a remote endpoint.
|
|
171
|
+
const webSearch = trusted ? resolvedCatalog?.webSearch : userCatalog?.webSearch;
|
|
172
|
+
return {
|
|
173
|
+
catalog: resolvedCatalog,
|
|
174
|
+
configSource,
|
|
175
|
+
configPath,
|
|
176
|
+
trustedMcp: trusted,
|
|
177
|
+
trustedPlugins: trusted,
|
|
178
|
+
...(webSearch ? { webSearch } : {}),
|
|
179
|
+
...(hasMergedMcp ? { mcpServers: mergedMcpServers, mcpServerMeta } : {}),
|
|
180
|
+
...(projectMcp.error ? { mcpJsonError: projectMcp.error } : {}),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function invalid() {
|
|
184
|
+
return new RuntimeError('INVALID_CONFIG', 'Invalid Host configuration');
|
|
185
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { RunId, ToolBinding } from '@saturn-universe/core';
|
|
2
|
+
import type { ToolConfiguration } from './cordis/tools/tools-core-plugin.js';
|
|
3
|
+
export { interactiveToolPolicies, isInteractiveToolPolicy, legacyInteractiveToolPolicies, plannerWorkspaceTools, } from './cordis/tools/tools-core-plugin.js';
|
|
4
|
+
/** Compatibility entry point for callers that need only the Host's tool services. */
|
|
5
|
+
export declare function openHostTools(root: string, config: ToolConfiguration, trustedConfig: boolean, hash: (value: unknown) => string, resultReader?: ToolBinding, getRunDeadline?: (runId: string) => Promise<number | undefined>, onProcessRecordError?: (processId: string, message: string) => void, previousDataReview?: (runId: RunId) => Promise<boolean>): Promise<{
|
|
6
|
+
registry: import("@saturn-universe/tools").Registry;
|
|
7
|
+
policy: import("@saturn-universe/core").ToolPermissionPolicy;
|
|
8
|
+
mcpServers: import("@saturn-universe/protocol").HostMcpServerSummary[];
|
|
9
|
+
defaultVersion: (capabilities: import("@saturn-universe/core").ModelCapabilities) => string;
|
|
10
|
+
plannerVersion: (capabilities: import("@saturn-universe/core").ModelCapabilities) => "1" | "planner";
|
|
11
|
+
freeze: (runConfig: import("@saturn-universe/core").RunConfig, target?: import("./cordis/scoped-layers.js").ContributionTarget) => Pick<import("@saturn-universe/core").RunConfig, "toolSnapshot"> & {
|
|
12
|
+
pluginBindings: NonNullable<import("@saturn-universe/core").RunConfig["pluginBindings"]>;
|
|
13
|
+
};
|
|
14
|
+
freezeWorker: (runConfig: import("@saturn-universe/core").RunConfig, team: import("@saturn-universe/core").TeamConfig, agentSessionId?: import("@saturn-universe/core").AgentSessionId, capabilities?: import("@saturn-universe/core").ModelCapabilities, options?: {
|
|
15
|
+
readonly depth?: number;
|
|
16
|
+
}) => Promise<import("@saturn-universe/core").RunConfig>;
|
|
17
|
+
processManager: import("@saturn-universe/tools").ProcessManager | undefined;
|
|
18
|
+
close: () => Promise<void>;
|
|
19
|
+
}>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createPluginContext, startRequiredPlugins } from './cordis/host-context.js';
|
|
2
|
+
import { createToolPlugins } from './cordis/tools/index.js';
|
|
3
|
+
export { interactiveToolPolicies, isInteractiveToolPolicy, legacyInteractiveToolPolicies, plannerWorkspaceTools, } from './cordis/tools/tools-core-plugin.js';
|
|
4
|
+
/** Compatibility entry point for callers that need only the Host's tool services. */
|
|
5
|
+
export async function openHostTools(root, config, trustedConfig, hash, resultReader, getRunDeadline, onProcessRecordError, previousDataReview) {
|
|
6
|
+
const plugins = createToolPlugins(root, {
|
|
7
|
+
config,
|
|
8
|
+
trustedConfig,
|
|
9
|
+
hash,
|
|
10
|
+
...(resultReader ? { resultReader } : {}),
|
|
11
|
+
...(previousDataReview ? { previousDataReview } : {}),
|
|
12
|
+
processManager: {
|
|
13
|
+
...(getRunDeadline ? { getRunDeadline } : {}),
|
|
14
|
+
...(onProcessRecordError ? { onRecordError: onProcessRecordError } : {}),
|
|
15
|
+
},
|
|
16
|
+
});
|
|
17
|
+
const { ctx, dispose } = await startRequiredPlugins(createPluginContext(), plugins);
|
|
18
|
+
const { registry, policy, mcpServers, defaultVersion, plannerVersion, freeze, freezeWorker } = ctx.saturnTools;
|
|
19
|
+
return {
|
|
20
|
+
registry,
|
|
21
|
+
policy,
|
|
22
|
+
mcpServers,
|
|
23
|
+
defaultVersion,
|
|
24
|
+
plannerVersion,
|
|
25
|
+
freeze,
|
|
26
|
+
freezeWorker,
|
|
27
|
+
processManager: ctx.saturnProcessManager,
|
|
28
|
+
close: dispose,
|
|
29
|
+
};
|
|
30
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createServer } from 'node:net';
|
|
3
|
+
import { mkdir, realpath, chmod, lstat, unlink } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { randomUUID } from 'node:crypto';
|
|
7
|
+
import { RuntimeError, sameWorkspaceRootUri } from '@saturn-universe/core';
|
|
8
|
+
import { openSqliteStore } from '@saturn-universe/storage';
|
|
9
|
+
import { resolveHostEndpoint } from '@saturn-universe/protocol';
|
|
10
|
+
import { acquireOwnership } from './ownership.js';
|
|
11
|
+
import { composeRuntime } from './composition.js';
|
|
12
|
+
import { ReplyWriter, receiveCommands } from './ipc.js';
|
|
13
|
+
import { createCommandDispatch } from './command-dispatch.js';
|
|
14
|
+
import { parseHostArguments } from './host-configuration.js';
|
|
15
|
+
import { createHostLogger, openHostDiagnostics } from './logger.js';
|
|
16
|
+
async function main() {
|
|
17
|
+
const startup = performance.now();
|
|
18
|
+
const args = parseHostArguments(process.argv.slice(2));
|
|
19
|
+
const root = await realpath(path.resolve(args.root));
|
|
20
|
+
const dataDir = path.join(root, '.saturn');
|
|
21
|
+
await mkdir(dataDir, { recursive: true });
|
|
22
|
+
const { key, endpoint } = resolveHostEndpoint(root);
|
|
23
|
+
const ownership = await acquireOwnership(key, dataDir);
|
|
24
|
+
const diagnostics = openHostDiagnostics(dataDir);
|
|
25
|
+
const startupLogger = createHostLogger([], diagnostics.destination);
|
|
26
|
+
let store;
|
|
27
|
+
let closeRuntime;
|
|
28
|
+
try {
|
|
29
|
+
const opening = performance.now();
|
|
30
|
+
store = await openSqliteStore({
|
|
31
|
+
filename: path.join(dataDir, 'runtime.sqlite'),
|
|
32
|
+
artifactRoot: path.join(dataDir, 'artifacts'),
|
|
33
|
+
instanceId: randomUUID(),
|
|
34
|
+
});
|
|
35
|
+
const storageMs = Math.round(performance.now() - opening);
|
|
36
|
+
const rootUri = pathToFileURL(root).href;
|
|
37
|
+
if ((await store.workspaceRoots()).some((uri) => !sameWorkspaceRootUri(uri, rootUri)))
|
|
38
|
+
throw new RuntimeError('WORKSPACE_MISMATCH', 'database belongs to another root');
|
|
39
|
+
const runtime = await composeRuntime(store, root, args, diagnostics.destination);
|
|
40
|
+
closeRuntime = runtime.close;
|
|
41
|
+
await runtime.recover();
|
|
42
|
+
let latestCursor = await store.head();
|
|
43
|
+
const unsubscribeCursor = store.subscribe((cursor) => {
|
|
44
|
+
latestCursor = cursor;
|
|
45
|
+
});
|
|
46
|
+
const statusSnapshot = () => ({ epoch: store.epoch, cursor: latestCursor, ...runtime.status });
|
|
47
|
+
const sockets = new Set();
|
|
48
|
+
const commands = createCommandDispatch({ execute: runtime.handle, status: statusSnapshot, shutdown });
|
|
49
|
+
const writers = new Map();
|
|
50
|
+
let closing = false;
|
|
51
|
+
const server = createServer((socket) => {
|
|
52
|
+
if (closing) {
|
|
53
|
+
socket.end();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
sockets.add(socket);
|
|
57
|
+
const writer = new ReplyWriter(socket);
|
|
58
|
+
writers.set(socket, writer);
|
|
59
|
+
socket.on('error', () => { });
|
|
60
|
+
socket.on('close', () => {
|
|
61
|
+
sockets.delete(socket);
|
|
62
|
+
writers.delete(socket);
|
|
63
|
+
});
|
|
64
|
+
receiveCommands(socket, writer, commands.submit, failure);
|
|
65
|
+
});
|
|
66
|
+
if (process.platform !== 'win32') {
|
|
67
|
+
const stale = await lstat(endpoint).catch(() => undefined);
|
|
68
|
+
if (stale) {
|
|
69
|
+
if (!stale.isSocket())
|
|
70
|
+
throw new RuntimeError('IPC_PATH_EXISTS', 'IPC endpoint is not a stale socket');
|
|
71
|
+
await unlink(endpoint).catch(() => {
|
|
72
|
+
throw new RuntimeError('IPC_PATH_EXISTS', 'Stale IPC socket could not be removed');
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
await new Promise((resolve, reject) => {
|
|
77
|
+
server.once('error', reject);
|
|
78
|
+
server.listen(endpoint, () => resolve());
|
|
79
|
+
});
|
|
80
|
+
if (process.platform !== 'win32')
|
|
81
|
+
await chmod(endpoint, 0o600);
|
|
82
|
+
// Composition awaits external module imports and Cordis startup before IPC opens.
|
|
83
|
+
startupLogger.info({ storageMs, ...store.startupTimings, hostReadyMs: Math.round(performance.now() - startup) }, 'Host ready');
|
|
84
|
+
process.stdout.write(JSON.stringify({
|
|
85
|
+
ready: true,
|
|
86
|
+
endpoint,
|
|
87
|
+
epoch: store.epoch,
|
|
88
|
+
status: statusSnapshot(),
|
|
89
|
+
}) + '\n');
|
|
90
|
+
void ownership.lost.then(() => shutdown());
|
|
91
|
+
async function shutdown() {
|
|
92
|
+
if (closing)
|
|
93
|
+
return;
|
|
94
|
+
closing = true;
|
|
95
|
+
unsubscribeCursor();
|
|
96
|
+
server.close();
|
|
97
|
+
await commands.close();
|
|
98
|
+
await Promise.all([...writers.values()].map((writer) => writer.drain()));
|
|
99
|
+
for (const socket of sockets)
|
|
100
|
+
socket.end();
|
|
101
|
+
await runtime.close();
|
|
102
|
+
await store.close();
|
|
103
|
+
diagnostics.close();
|
|
104
|
+
await ownership.release();
|
|
105
|
+
}
|
|
106
|
+
process.once('SIGINT', () => void shutdown());
|
|
107
|
+
process.once('SIGTERM', () => void shutdown());
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
try {
|
|
111
|
+
await closeRuntime?.();
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await store?.close();
|
|
115
|
+
await ownership.release();
|
|
116
|
+
}
|
|
117
|
+
diagnostics.close();
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function failure(requestId, error) {
|
|
122
|
+
return {
|
|
123
|
+
requestId,
|
|
124
|
+
ok: false,
|
|
125
|
+
error: {
|
|
126
|
+
code: error instanceof RuntimeError ? error.code : 'INTERNAL',
|
|
127
|
+
message: `Command failed [diagnosticId: ${randomUUID()}]`,
|
|
128
|
+
retryable: error instanceof RuntimeError &&
|
|
129
|
+
['VERSION_CONFLICT', 'STORAGE_BUSY', 'HOST_BUSY'].includes(error.code),
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
main().catch((error) => {
|
|
134
|
+
process.stderr.write(JSON.stringify({
|
|
135
|
+
error: error instanceof RuntimeError ? error.code : 'HOST_START_FAILED',
|
|
136
|
+
message: error instanceof RuntimeError ? error.message : 'Host failed',
|
|
137
|
+
diagnosticId: randomUUID(),
|
|
138
|
+
}) + '\n');
|
|
139
|
+
process.exitCode = 1;
|
|
140
|
+
});
|
package/dist/ipc.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Socket } from 'node:net';
|
|
2
|
+
import { decodeCommand } from '@saturn-universe/protocol';
|
|
3
|
+
import type { ProtocolReply } from '@saturn-universe/protocol';
|
|
4
|
+
export declare class CommandQueue {
|
|
5
|
+
private readonly limit;
|
|
6
|
+
private tail;
|
|
7
|
+
private pending;
|
|
8
|
+
private closing;
|
|
9
|
+
constructor(limit?: number);
|
|
10
|
+
submit<T>(work: () => Promise<T>): Promise<T>;
|
|
11
|
+
close(): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
export declare class ReplyWriter {
|
|
14
|
+
private readonly socket;
|
|
15
|
+
private tail;
|
|
16
|
+
private bytes;
|
|
17
|
+
private pending;
|
|
18
|
+
private closing;
|
|
19
|
+
constructor(socket: Socket);
|
|
20
|
+
write(reply: ProtocolReply): boolean;
|
|
21
|
+
end(reply?: ProtocolReply): void;
|
|
22
|
+
drain(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export declare function receiveCommands(socket: Socket, writer: ReplyWriter, handle: (request: ReturnType<typeof decodeCommand>, connection: AbortSignal) => Promise<ProtocolReply>, failure: (requestId: string, error: unknown) => ProtocolReply): void;
|
package/dist/ipc.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
2
|
+
import { decodeCommand, encodeReply, IpcFrameReader, maxFrameBytes } from '@saturn-universe/protocol';
|
|
3
|
+
export class CommandQueue {
|
|
4
|
+
limit;
|
|
5
|
+
tail = Promise.resolve();
|
|
6
|
+
pending = 0;
|
|
7
|
+
closing = false;
|
|
8
|
+
constructor(limit = 64) {
|
|
9
|
+
this.limit = limit;
|
|
10
|
+
}
|
|
11
|
+
submit(work) {
|
|
12
|
+
if (this.closing)
|
|
13
|
+
return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
|
|
14
|
+
if (this.pending >= this.limit)
|
|
15
|
+
return Promise.reject(new RuntimeError('HOST_BUSY', 'Host queue is full'));
|
|
16
|
+
this.pending++;
|
|
17
|
+
const result = this.tail.then(work);
|
|
18
|
+
this.tail = result
|
|
19
|
+
.then(() => undefined, () => undefined)
|
|
20
|
+
.finally(() => this.pending--);
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
async close() {
|
|
24
|
+
this.closing = true;
|
|
25
|
+
await this.tail;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export class ReplyWriter {
|
|
29
|
+
socket;
|
|
30
|
+
tail = Promise.resolve();
|
|
31
|
+
bytes = 0;
|
|
32
|
+
pending = 0;
|
|
33
|
+
closing = false;
|
|
34
|
+
constructor(socket) {
|
|
35
|
+
this.socket = socket;
|
|
36
|
+
}
|
|
37
|
+
write(reply) {
|
|
38
|
+
if (this.closing || this.socket.destroyed || !this.socket.writable)
|
|
39
|
+
return false;
|
|
40
|
+
let frame = encodeReply(reply);
|
|
41
|
+
if (Buffer.byteLength(frame) > maxFrameBytes)
|
|
42
|
+
frame = encodeReply({
|
|
43
|
+
requestId: reply.requestId,
|
|
44
|
+
ok: false,
|
|
45
|
+
error: { code: 'REPLY_TOO_LARGE', message: 'Host reply exceeds frame limit', retryable: false },
|
|
46
|
+
});
|
|
47
|
+
const length = Buffer.byteLength(frame);
|
|
48
|
+
if (this.pending >= 64 || this.bytes + length > 2 * maxFrameBytes) {
|
|
49
|
+
this.end({
|
|
50
|
+
requestId: reply.requestId,
|
|
51
|
+
ok: false,
|
|
52
|
+
error: { code: 'HOST_BUSY', message: 'Reply queue is full', retryable: true },
|
|
53
|
+
});
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
this.pending++;
|
|
57
|
+
this.bytes += length;
|
|
58
|
+
this.tail = this.tail
|
|
59
|
+
.then(() => writeReply(this.socket, frame))
|
|
60
|
+
.catch(() => {
|
|
61
|
+
this.socket.destroy();
|
|
62
|
+
})
|
|
63
|
+
.finally(() => {
|
|
64
|
+
this.pending--;
|
|
65
|
+
this.bytes -= length;
|
|
66
|
+
});
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
end(reply) {
|
|
70
|
+
if (this.closing)
|
|
71
|
+
return;
|
|
72
|
+
this.closing = true;
|
|
73
|
+
this.socket.pause();
|
|
74
|
+
this.tail = this.tail
|
|
75
|
+
.then(async () => {
|
|
76
|
+
if (reply)
|
|
77
|
+
await writeReply(this.socket, encodeReply(reply));
|
|
78
|
+
this.socket.end();
|
|
79
|
+
})
|
|
80
|
+
.catch(() => {
|
|
81
|
+
this.socket.destroy();
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
async drain() {
|
|
85
|
+
await this.tail;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function writeReply(socket, frame) {
|
|
89
|
+
if (socket.destroyed || !socket.writable)
|
|
90
|
+
throw new Error('Reply socket is closed');
|
|
91
|
+
if (socket.write(frame))
|
|
92
|
+
return;
|
|
93
|
+
await new Promise((resolve, reject) => {
|
|
94
|
+
const cleanup = () => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
socket.off('drain', drained);
|
|
97
|
+
socket.off('close', closed);
|
|
98
|
+
socket.off('error', failed);
|
|
99
|
+
};
|
|
100
|
+
const drained = () => {
|
|
101
|
+
cleanup();
|
|
102
|
+
resolve();
|
|
103
|
+
};
|
|
104
|
+
const closed = () => {
|
|
105
|
+
cleanup();
|
|
106
|
+
reject(new Error('Reply socket closed before draining'));
|
|
107
|
+
};
|
|
108
|
+
const failed = (error) => {
|
|
109
|
+
cleanup();
|
|
110
|
+
reject(error);
|
|
111
|
+
};
|
|
112
|
+
const timer = setTimeout(() => failed(new Error('Reply drain timed out')), 5000);
|
|
113
|
+
socket.once('drain', drained);
|
|
114
|
+
socket.once('close', closed);
|
|
115
|
+
socket.once('error', failed);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
export function receiveCommands(socket, writer, handle, failure) {
|
|
119
|
+
const reader = new IpcFrameReader(maxFrameBytes);
|
|
120
|
+
const connection = new AbortController();
|
|
121
|
+
socket.once('close', () => connection.abort());
|
|
122
|
+
let rejected = false;
|
|
123
|
+
const pending = new Set();
|
|
124
|
+
socket.setEncoding('utf8');
|
|
125
|
+
socket.on('data', (chunk) => {
|
|
126
|
+
if (rejected)
|
|
127
|
+
return;
|
|
128
|
+
reader.append(String(chunk));
|
|
129
|
+
let frame;
|
|
130
|
+
while ((frame = reader.take()) !== undefined) {
|
|
131
|
+
if (frame === null) {
|
|
132
|
+
rejectFrame();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
let request;
|
|
136
|
+
try {
|
|
137
|
+
request = decodeCommand(frame);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
writer.write(failure('unknown', error));
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const work = handle(request, connection.signal)
|
|
144
|
+
.then((reply) => {
|
|
145
|
+
writer.write(reply);
|
|
146
|
+
}, (error) => {
|
|
147
|
+
writer.write(failure(request.requestId, error));
|
|
148
|
+
})
|
|
149
|
+
.finally(() => pending.delete(work));
|
|
150
|
+
pending.add(work);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
function rejectFrame() {
|
|
154
|
+
rejected = true;
|
|
155
|
+
socket.pause();
|
|
156
|
+
void Promise.all(pending).then(() => writer.end({
|
|
157
|
+
requestId: 'unknown',
|
|
158
|
+
ok: false,
|
|
159
|
+
error: { code: 'INVALID_COMMAND', message: 'frame too large', retryable: false },
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { DestinationStream } from 'pino';
|
|
2
|
+
import type { LoggerPort } from '@saturn-universe/core';
|
|
3
|
+
import { redactExportValue } from '@saturn-universe/protocol';
|
|
4
|
+
export { redactExportValue };
|
|
5
|
+
export declare function openHostDiagnostics(directory: string): {
|
|
6
|
+
destination: {
|
|
7
|
+
write(line: string): boolean;
|
|
8
|
+
};
|
|
9
|
+
close(): void;
|
|
10
|
+
};
|
|
11
|
+
export declare function createHostLogger(secrets: readonly string[], destination?: DestinationStream): LoggerPort;
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
import { redactExportValue } from '@saturn-universe/protocol';
|
|
3
|
+
import { closeSync, constants, fstatSync, ftruncateSync, lstatSync, openSync, writeSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
export { redactExportValue };
|
|
6
|
+
export function openHostDiagnostics(directory) {
|
|
7
|
+
const filename = path.join(directory, 'host-diagnostics.jsonl');
|
|
8
|
+
let file;
|
|
9
|
+
let size = 0;
|
|
10
|
+
try {
|
|
11
|
+
const existing = lstatSync(filename, { throwIfNoEntry: false });
|
|
12
|
+
if (!existing || (existing.isFile() && existing.nlink === 1)) {
|
|
13
|
+
file = openSync(filename, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0), 0o600);
|
|
14
|
+
const stat = fstatSync(file);
|
|
15
|
+
if (!stat.isFile() || stat.nlink !== 1) {
|
|
16
|
+
closeSync(file);
|
|
17
|
+
file = undefined;
|
|
18
|
+
}
|
|
19
|
+
else {
|
|
20
|
+
size = stat.size;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
if (file !== undefined)
|
|
26
|
+
closeSync(file);
|
|
27
|
+
file = undefined;
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
destination: {
|
|
31
|
+
write(line) {
|
|
32
|
+
if (file === undefined)
|
|
33
|
+
return process.stderr.write(line);
|
|
34
|
+
try {
|
|
35
|
+
const bytes = Buffer.byteLength(line);
|
|
36
|
+
if (size + bytes > 1024 * 1024) {
|
|
37
|
+
ftruncateSync(file, 0);
|
|
38
|
+
size = 0;
|
|
39
|
+
}
|
|
40
|
+
size += writeSync(file, line);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
process.stderr.write(line);
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
close() {
|
|
49
|
+
if (file !== undefined)
|
|
50
|
+
closeSync(file);
|
|
51
|
+
file = undefined;
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function createHostLogger(secrets, destination = process.stderr) {
|
|
56
|
+
const log = pino({ base: null, timestamp: pino.stdTimeFunctions.isoTime }, destination);
|
|
57
|
+
const redact = (text) => redactExportValue(text, secrets).slice(0, 4096);
|
|
58
|
+
const sanitize = (value, depth = 0) => {
|
|
59
|
+
if (typeof value === 'string')
|
|
60
|
+
return redact(value);
|
|
61
|
+
if (value === null || typeof value !== 'object')
|
|
62
|
+
return value;
|
|
63
|
+
if (depth >= 4)
|
|
64
|
+
return '[TRUNCATED]';
|
|
65
|
+
if (Array.isArray(value))
|
|
66
|
+
return value.slice(0, 32).map((item) => sanitize(item, depth + 1));
|
|
67
|
+
return Object.fromEntries(Object.entries(value)
|
|
68
|
+
.slice(0, 32)
|
|
69
|
+
.map(([key, item]) => [
|
|
70
|
+
redact(key),
|
|
71
|
+
/auth|api.?key|token|secret|password|cookie|headers|arguments|input|output/i.test(key)
|
|
72
|
+
? '[REDACTED]'
|
|
73
|
+
: sanitize(item, depth + 1),
|
|
74
|
+
]));
|
|
75
|
+
};
|
|
76
|
+
return {
|
|
77
|
+
info(fields, message) {
|
|
78
|
+
log.info(sanitize(fields), redact(message));
|
|
79
|
+
},
|
|
80
|
+
error(fields, message) {
|
|
81
|
+
log.error(sanitize(fields), redact(message));
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const mcpServersSchema: z.ZodRecord<z.ZodString, z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
3
|
+
tools: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
4
|
+
read_only_tools: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
5
|
+
timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
6
|
+
transport: z.ZodLiteral<"stdio">;
|
|
7
|
+
command: z.ZodString;
|
|
8
|
+
args: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
9
|
+
env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
10
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
11
|
+
tools: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
12
|
+
read_only_tools: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
13
|
+
timeout_ms: z.ZodOptional<z.ZodNumber>;
|
|
14
|
+
transport: z.ZodLiteral<"http">;
|
|
15
|
+
url: z.ZodString;
|
|
16
|
+
headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
17
|
+
}, z.core.$strict>], "transport">>;
|