@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,15 @@
1
+ export interface SessionPaths {
2
+ readonly sessionDir: string;
3
+ readonly assetsDir: string;
4
+ readonly pluginsDir: string;
5
+ readonly sandboxesDir: string;
6
+ readonly processesDir: string;
7
+ }
8
+ export interface PluginSessionPaths {
9
+ readonly sessionDir: string;
10
+ readonly assetsDir: string;
11
+ readonly pluginDataDir: string;
12
+ }
13
+ export declare function sanitizeSessionSegment(value: string): string;
14
+ export declare function resolveSessionPaths(workspaceRoot: string, sessionId: string): SessionPaths;
15
+ export declare function resolvePluginSessionPaths(workspaceRoot: string, sessionId: string, pluginId: string): PluginSessionPaths;
@@ -0,0 +1,40 @@
1
+ import path from 'node:path';
2
+ import { isContainedPath } from '@saturn-universe/tools';
3
+ export function sanitizeSessionSegment(value) {
4
+ const trimmed = value.trim();
5
+ if (!trimmed || trimmed === '.' || trimmed === '..' || trimmed.length > 128) {
6
+ throw new Error(`Invalid session path segment: "${value}"`);
7
+ }
8
+ if (!/^[A-Za-z0-9._-]+$/u.test(trimmed) || trimmed.includes('..')) {
9
+ throw new Error(`Invalid session path segment: "${value}"`);
10
+ }
11
+ return trimmed;
12
+ }
13
+ export function resolveSessionPaths(workspaceRoot, sessionId) {
14
+ const safeSession = sanitizeSessionSegment(sessionId);
15
+ const resolvedRoot = path.resolve(workspaceRoot);
16
+ const sessionDir = path.join(resolvedRoot, '.saturn', 'sessions', safeSession);
17
+ if (!isContainedPath(resolvedRoot, sessionDir)) {
18
+ throw new Error(`Session path escapes workspace root: "${sessionId}"`);
19
+ }
20
+ return {
21
+ sessionDir,
22
+ assetsDir: path.join(sessionDir, 'assets'),
23
+ pluginsDir: path.join(sessionDir, 'plugins'),
24
+ sandboxesDir: path.join(sessionDir, 'sandboxes'),
25
+ processesDir: path.join(sessionDir, 'processes'),
26
+ };
27
+ }
28
+ export function resolvePluginSessionPaths(workspaceRoot, sessionId, pluginId) {
29
+ const safePlugin = sanitizeSessionSegment(pluginId);
30
+ const paths = resolveSessionPaths(workspaceRoot, sessionId);
31
+ const pluginDataDir = path.join(paths.pluginsDir, safePlugin);
32
+ if (!isContainedPath(paths.pluginsDir, pluginDataDir)) {
33
+ throw new Error(`Plugin session path escapes session plugins root: "${pluginId}"`);
34
+ }
35
+ return {
36
+ sessionDir: paths.sessionDir,
37
+ assetsDir: paths.assetsDir,
38
+ pluginDataDir,
39
+ };
40
+ }
@@ -0,0 +1,14 @@
1
+ import type { AgentExecutionScope, ContextAssembly, Hash, ModelGateway, RequestId, RunConfig, TurnId } from '@saturn-universe/core';
2
+ import type { HostCommandResults } from '@saturn-universe/protocol';
3
+ export declare function answerSideQuestion({ gateway, hash, signal, requestId, }: {
4
+ gateway: ModelGateway;
5
+ hash: Hash;
6
+ signal: AbortSignal;
7
+ requestId: RequestId;
8
+ }, { assembly, config, route, turnId, question, }: {
9
+ assembly: ContextAssembly;
10
+ config: RunConfig;
11
+ route: AgentExecutionScope;
12
+ turnId: TurnId;
13
+ question: string;
14
+ }): Promise<HostCommandResults['session.btw']>;
@@ -0,0 +1,89 @@
1
+ import { modelConfiguration, RuntimeError } from '@saturn-universe/core';
2
+ export async function answerSideQuestion({ gateway, hash, signal, requestId, }, { assembly, config, route, turnId, question, }) {
3
+ const { binding, model } = assembly;
4
+ const { capabilities } = await gateway.describe(model);
5
+ const { instructionPlacement, reasoningModel, reasoningEfforts } = capabilities.responses;
6
+ const reasoning = reasoningModel
7
+ ? ['minimal', 'low'].find((effort) => reasoningEfforts.includes(effort))
8
+ : undefined;
9
+ const responsesOptions = {
10
+ storage: 'local_stateless',
11
+ ...(reasoning ? { reasoning: { effort: reasoning } } : {}),
12
+ };
13
+ const instructions = assembly.messages
14
+ .flatMap((message) => (message.role === 'system' ? [message.content] : []))
15
+ .join('\n\n');
16
+ const boundary = [
17
+ 'This is a temporary side question. Answer only the side question below, briefly.',
18
+ 'No tools are available. Do not continue, change, or take any action on the main task.',
19
+ 'Use the preceding conversation as read-only context.',
20
+ '',
21
+ question,
22
+ ].join('\n');
23
+ const fullInput = [
24
+ ...assembly.responses.fullInput,
25
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: boundary }] },
26
+ ];
27
+ const output = { kind: 'text' };
28
+ const configurationDigest = hash(modelConfiguration({
29
+ binding,
30
+ instructions,
31
+ placement: instructionPlacement,
32
+ tools: [],
33
+ output,
34
+ reasoning: responsesOptions.reasoning,
35
+ }));
36
+ const fullInputDigest = hash(fullInput);
37
+ const maxOutputTokens = Math.min(512, capabilities.maxOutputTokens);
38
+ const estimatedInputTokens = assembly.estimate.inputTokens + Math.ceil(boundary.length / 3);
39
+ const request = {
40
+ id: requestId,
41
+ callGroupId: requestId,
42
+ attempt: 1,
43
+ agentSessionId: route.agentSessionId,
44
+ runId: route.runId,
45
+ turnId,
46
+ model,
47
+ binding,
48
+ messages: [
49
+ ...assembly.messages,
50
+ { role: 'user', sourceBackgroundId: 'btw', content: [{ type: 'text', text: boundary }] },
51
+ ],
52
+ responses: {
53
+ ...assembly.responses,
54
+ epochId: hash({ requestId, configurationDigest, fullInputDigest }),
55
+ decision: { kind: 'new' },
56
+ configurationDigest,
57
+ fullInput,
58
+ fullInputDigest,
59
+ replaySources: [],
60
+ },
61
+ responsesOptions,
62
+ tools: [],
63
+ output,
64
+ maxOutputTokens,
65
+ budget: {
66
+ estimatedInputTokens,
67
+ reservedTotalTokens: estimatedInputTokens + maxOutputTokens,
68
+ accuracy: 'conservative_estimate',
69
+ },
70
+ context: {
71
+ surfaceSeq: assembly.surfaceSeq,
72
+ selectedMessageIds: assembly.selectedMessageIds,
73
+ assemblyHash: assembly.assemblyHash,
74
+ providerVersions: assembly.providerVersions,
75
+ },
76
+ };
77
+ const response = await gateway.generate(request, {
78
+ signal,
79
+ promptCacheOnly: true,
80
+ timeoutMs: Math.min(config.limits.modelTimeoutMs, 25_000),
81
+ });
82
+ const answer = response.content
83
+ .flatMap((part) => (part.type === 'text' ? [part.text] : []))
84
+ .join('\n')
85
+ .trim();
86
+ if (!answer)
87
+ throw new RuntimeError('BTW_NO_ANSWER', 'The provider returned no text for the side question');
88
+ return { answer };
89
+ }
@@ -0,0 +1,13 @@
1
+ import type { ModeDefinition, ToolBinding } from '@saturn-universe/core';
2
+ import type { DiscoveredSkill, DiscoveredSkillSummary, ModeSkillDirectory } from '@saturn-universe/protocol';
3
+ import type { ProviderCatalog } from './provider-catalog.js';
4
+ export declare const skillToolName = "skill";
5
+ export interface SkillRegistryService {
6
+ readonly skills: readonly DiscoveredSkill[];
7
+ summaries(): readonly DiscoveredSkillSummary[];
8
+ get(name: string): DiscoveredSkill | undefined;
9
+ indexSkills(disabledSkills?: readonly string[]): readonly DiscoveredSkillSummary[];
10
+ }
11
+ export declare function resolveModeSkillDirs(_activeMode: ModeDefinition, _catalog?: ProviderCatalog): readonly ModeSkillDirectory[];
12
+ export declare function createSkillRegistryService(workspaceRoot: string, activeMode: ModeDefinition, catalog?: ProviderCatalog, env?: NodeJS.ProcessEnv): Promise<SkillRegistryService>;
13
+ export declare function createNativeSkillTool(service: SkillRegistryService): ToolBinding;
@@ -0,0 +1,243 @@
1
+ import { constants as fsConstants } from 'node:fs';
2
+ import { open, readFile, realpath } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { discoverAgentSkills, isInsideSkillDir, validateRelativeSkillResourcePath, } from '@saturn-universe/protocol';
5
+ import { readFileWindow } from '@saturn-universe/tools';
6
+ export const skillToolName = 'skill';
7
+ const DEFAULT_RESOURCE_MAX_BYTES = 65536;
8
+ const HARD_RESOURCE_MAX_BYTES = 262144;
9
+ function utf8SequenceLength(leadByte) {
10
+ if ((leadByte & 0x80) === 0x00)
11
+ return 1;
12
+ if ((leadByte & 0xe0) === 0xc0)
13
+ return 2;
14
+ if ((leadByte & 0xf0) === 0xe0)
15
+ return 3;
16
+ if ((leadByte & 0xf8) === 0xf0)
17
+ return 4;
18
+ return 1;
19
+ }
20
+ function findUtf8SafeEnd(buffer, requestedEnd) {
21
+ const clampedEnd = Math.min(buffer.byteLength, requestedEnd);
22
+ if (clampedEnd === 0 || clampedEnd === buffer.byteLength)
23
+ return clampedEnd;
24
+ const minScan = Math.max(0, clampedEnd - 3);
25
+ for (let pos = clampedEnd - 1; pos >= minScan; pos -= 1) {
26
+ const byte = buffer[pos];
27
+ if ((byte & 0xc0) === 0x80)
28
+ continue;
29
+ const seqLen = utf8SequenceLength(byte);
30
+ if (pos + seqLen > clampedEnd) {
31
+ return pos > 0 ? pos : Math.min(buffer.byteLength, seqLen);
32
+ }
33
+ return clampedEnd;
34
+ }
35
+ return clampedEnd;
36
+ }
37
+ function errorObservation(code, message) {
38
+ return {
39
+ effect: 'none',
40
+ outcome: {
41
+ status: 'error',
42
+ error: { code, message, retryable: false },
43
+ },
44
+ };
45
+ }
46
+ export function resolveModeSkillDirs(_activeMode, _catalog) {
47
+ return [];
48
+ }
49
+ export async function createSkillRegistryService(workspaceRoot, activeMode, catalog, env = process.env) {
50
+ const modeSkillDirs = resolveModeSkillDirs(activeMode, catalog);
51
+ const skills = await discoverAgentSkills(workspaceRoot, {
52
+ env,
53
+ modeSkillDirs,
54
+ ...(catalog?.skills ? { explicitSkills: catalog.skills } : {}),
55
+ });
56
+ const byName = new Map(skills.map((skill) => [skill.name, skill]));
57
+ const summaryOf = (skill) => ({
58
+ name: skill.name,
59
+ description: skill.description,
60
+ scope: skill.scope,
61
+ source: skill.source,
62
+ resources: [...skill.resources],
63
+ ...(skill.ref ? { ref: skill.ref } : {}),
64
+ ...(skill.license ? { license: skill.license } : {}),
65
+ ...(skill.compatibility ? { compatibility: skill.compatibility } : {}),
66
+ ...(skill.allowedTools ? { allowedTools: skill.allowedTools } : {}),
67
+ ...(skill.indexedBySecurityPlugin ? { indexedBySecurityPlugin: true } : {}),
68
+ });
69
+ const summariesList = skills.map(summaryOf);
70
+ return {
71
+ skills,
72
+ summaries: () => summariesList,
73
+ get: (name) => byName.get(name),
74
+ indexSkills(disabledSkills) {
75
+ const disabled = disabledSkills?.length ? new Set(disabledSkills) : undefined;
76
+ return summariesList.filter((item) => !item.indexedBySecurityPlugin && (!disabled || !disabled.has(item.name)));
77
+ },
78
+ };
79
+ }
80
+ export function createNativeSkillTool(service) {
81
+ return {
82
+ definition: {
83
+ name: skillToolName,
84
+ version: '1',
85
+ description: 'Progressively discover, load, and read Agent Skills (`SKILL.md` instructions and sibling `references/` or `scripts/` files). Call `action="list"` to inspect available skills, `action="load"` with `skill` to load full `SKILL.md` instructions, or `action="read_resource"` with `skill` and `path` to read a specific resource file.',
86
+ inputSchema: {
87
+ type: 'object',
88
+ properties: {
89
+ action: {
90
+ type: 'string',
91
+ enum: ['list', 'load', 'read_resource', 'read_ref'],
92
+ },
93
+ skill: { type: 'string', minLength: 1, maxLength: 128 },
94
+ path: { type: 'string', minLength: 1, maxLength: 512 },
95
+ offset: { type: 'integer', minimum: 0 },
96
+ max_bytes: { type: 'integer', minimum: 1, maximum: HARD_RESOURCE_MAX_BYTES },
97
+ },
98
+ required: ['action'],
99
+ additionalProperties: false,
100
+ },
101
+ source: { kind: 'builtin' },
102
+ effects: 'read',
103
+ supportsIdempotencyKey: false,
104
+ supportsReconcile: false,
105
+ concurrency: 'parallel',
106
+ timeoutMs: 10000,
107
+ },
108
+ handler: {
109
+ async invoke(rawInput) {
110
+ if (!rawInput || typeof rawInput !== 'object' || Array.isArray(rawInput)) {
111
+ return errorObservation('INVALID_INPUT', 'Expected an object payload for skill.');
112
+ }
113
+ const input = rawInput;
114
+ const action = typeof input.action === 'string' ? input.action.trim() : '';
115
+ if (action === 'list') {
116
+ const items = service.summaries().map((item) => ({
117
+ name: item.name,
118
+ description: item.description,
119
+ scope: item.scope,
120
+ source: item.source,
121
+ resources: [...item.resources],
122
+ }));
123
+ const text = items.length
124
+ ? items
125
+ .map((item) => `- ${item.name} [${item.scope}]: ${item.description}${item.resources.length ? ` (${item.resources.length} resources)` : ''}`)
126
+ .join('\n')
127
+ : 'No agent skills discovered.';
128
+ return {
129
+ effect: 'none',
130
+ outcome: {
131
+ status: 'success',
132
+ content: [{ type: 'text', text }],
133
+ data: { skills: items },
134
+ },
135
+ };
136
+ }
137
+ if (action !== 'load' && action !== 'read_resource' && action !== 'read_ref') {
138
+ return errorObservation('INVALID_INPUT', 'action must be one of "list", "load", or "read_resource".');
139
+ }
140
+ const skillName = typeof input.skill === 'string' ? input.skill.trim() : '';
141
+ if (!skillName) {
142
+ return errorObservation('INVALID_INPUT', 'skill is required for this action.');
143
+ }
144
+ const skill = service.get(skillName);
145
+ if (!skill) {
146
+ return errorObservation('SKILL_NOT_FOUND', `Unknown skill: ${skillName}`);
147
+ }
148
+ if (action === 'load') {
149
+ let manifestReal;
150
+ try {
151
+ manifestReal = await realpath(skill.skillFilePath);
152
+ }
153
+ catch {
154
+ return errorObservation('NOT_FOUND', `Skill manifest not found for ${skill.name}`);
155
+ }
156
+ if (!isInsideSkillDir(skill.rootDir, manifestReal) && manifestReal !== skill.skillFilePath) {
157
+ return errorObservation('PATH_TRAVERSAL_DENIED', 'Skill entrypoint resolves outside the skill directory.');
158
+ }
159
+ const content = await readFile(manifestReal, 'utf8');
160
+ return {
161
+ effect: 'none',
162
+ outcome: {
163
+ status: 'success',
164
+ content: [{ type: 'text', text: content }],
165
+ data: {
166
+ skill: skill.name,
167
+ scope: skill.scope,
168
+ source: skill.source,
169
+ description: skill.description,
170
+ resources: [...skill.resources],
171
+ content,
172
+ },
173
+ },
174
+ };
175
+ }
176
+ const pathCheck = validateRelativeSkillResourcePath(input.path);
177
+ if (!pathCheck.ok) {
178
+ return errorObservation(pathCheck.code, pathCheck.message);
179
+ }
180
+ const offset = input.offset === undefined ? 0 : input.offset;
181
+ if (typeof offset !== 'number' || !Number.isSafeInteger(offset) || offset < 0) {
182
+ return errorObservation('INVALID_INPUT', 'offset must be a non-negative safe integer.');
183
+ }
184
+ const maxBytesInput = input.max_bytes === undefined ? DEFAULT_RESOURCE_MAX_BYTES : input.max_bytes;
185
+ if (typeof maxBytesInput !== 'number' || !Number.isSafeInteger(maxBytesInput) || maxBytesInput < 1) {
186
+ return errorObservation('INVALID_INPUT', 'max_bytes must be a positive safe integer.');
187
+ }
188
+ const maxBytes = Math.min(maxBytesInput, HARD_RESOURCE_MAX_BYTES);
189
+ const candidate = path.resolve(skill.rootDir, pathCheck.normalized);
190
+ if (!isInsideSkillDir(skill.rootDir, candidate)) {
191
+ return errorObservation('PATH_TRAVERSAL_DENIED', 'Requested path resolves outside the skill directory.');
192
+ }
193
+ let targetReal;
194
+ try {
195
+ targetReal = await realpath(candidate);
196
+ }
197
+ catch (error) {
198
+ if (error.code === 'ENOENT') {
199
+ return errorObservation('NOT_FOUND', `Resource file not found: ${pathCheck.normalized}`);
200
+ }
201
+ return errorObservation('READ_FAILED', `Could not resolve resource path: ${pathCheck.normalized}`);
202
+ }
203
+ if (!isInsideSkillDir(skill.rootDir, targetReal)) {
204
+ return errorObservation('PATH_TRAVERSAL_DENIED', 'Resolved symlink or path escapes the skill directory.');
205
+ }
206
+ const handle = await open(targetReal, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0)).catch(() => undefined);
207
+ try {
208
+ const info = await handle?.stat().catch(() => undefined);
209
+ if (!handle || !info) {
210
+ return errorObservation('READ_FAILED', `Could not inspect resource file: ${pathCheck.normalized}`);
211
+ }
212
+ if (!info.isFile()) {
213
+ return errorObservation('INVALID_PATH', `Requested path is not a regular file: ${pathCheck.normalized}`);
214
+ }
215
+ // Look ahead by at most three bytes to finish one UTF-8 character at the start of a page.
216
+ const length = Math.max(0, Math.min(info.size - offset, maxBytes + 3));
217
+ const buffer = await readFileWindow(handle, offset, length);
218
+ const bytesRead = findUtf8SafeEnd(buffer, maxBytes);
219
+ const content = buffer.toString('utf8', 0, bytesRead);
220
+ return {
221
+ effect: 'none',
222
+ outcome: {
223
+ status: 'success',
224
+ content: [{ type: 'text', text: content }],
225
+ data: {
226
+ skill: skill.name,
227
+ path: pathCheck.normalized,
228
+ offset,
229
+ totalBytes: info.size,
230
+ bytesRead,
231
+ truncated: offset + bytesRead < info.size,
232
+ content,
233
+ },
234
+ },
235
+ };
236
+ }
237
+ finally {
238
+ await handle?.close();
239
+ }
240
+ },
241
+ },
242
+ };
243
+ }
@@ -0,0 +1,3 @@
1
+ import type { TokenCounter } from '@saturn-universe/core';
2
+ export declare function estimateStringTokens(text: string, padding?: number): number;
3
+ export declare const responsesTokenCounter: TokenCounter;
@@ -0,0 +1,73 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ const CONSERVATIVE_MARGIN = 1.12;
3
+ const ASCII_BYTES_PER_TOKEN = 3.4;
4
+ const NON_ASCII_TOKENS_PER_CODEPOINT = 1.3;
5
+ export function estimateStringTokens(text, padding = 0.5) {
6
+ let asciiBytes = 0;
7
+ let nonAsciiCodepoints = 0;
8
+ for (let i = 0; i < text.length;) {
9
+ const code = text.codePointAt(i);
10
+ if (code < 0x80) {
11
+ asciiBytes++;
12
+ i++;
13
+ }
14
+ else {
15
+ nonAsciiCodepoints++;
16
+ i += code > 0xffff ? 2 : 1;
17
+ }
18
+ }
19
+ const raw = asciiBytes / ASCII_BYTES_PER_TOKEN + nonAsciiCodepoints * NON_ASCII_TOKENS_PER_CODEPOINT + padding;
20
+ return Math.max(1, Math.ceil(raw * CONSERVATIVE_MARGIN));
21
+ }
22
+ // Calibrated BPE-aware estimator with conservative margin. Charges logical fields and
23
+ // framing without 1-byte-per-token inflation or charging opaque IDs / encrypted blobs.
24
+ function visibleTokens(value) {
25
+ if (typeof value === 'string')
26
+ return estimateStringTokens(value);
27
+ if (value === null || typeof value !== 'object')
28
+ return Math.max(1, Math.ceil((String(value).length / ASCII_BYTES_PER_TOKEN + 0.5) * CONSERVATIVE_MARGIN));
29
+ if (Array.isArray(value))
30
+ return 1 + value.reduce((sum, entry) => sum + visibleTokens(entry), 0);
31
+ return (1 +
32
+ Object.entries(value).reduce((sum, [key, entry]) => sum + estimateStringTokens(key, 0) + visibleTokens(entry), 0));
33
+ }
34
+ function itemTokens(item) {
35
+ const { id: _id, call_id: _callId, encrypted_content: _encrypted, ...visible } = item;
36
+ return 10 + visibleTokens(visible);
37
+ }
38
+ export const responsesTokenCounter = {
39
+ async estimate({ responses, tools, replay, opaqueReasoningBounds }) {
40
+ const items = responses.fullInput;
41
+ let inputTokens;
42
+ if (replay) {
43
+ const replayedOutput = items.slice(replay.outputStart, replay.inputCount);
44
+ const framing = replayedOutput.length * 10;
45
+ const visibleOutput = replayedOutput.reduce((sum, item) => sum + itemTokens(item), 0);
46
+ // The previous reported input includes the unchanged instructions and tool schemas.
47
+ inputTokens =
48
+ Math.ceil(replay.usage.inputTokens * 1.1) +
49
+ Math.max(replay.usage.outputTokens + framing, visibleOutput) +
50
+ 32;
51
+ for (const item of items.slice(replay.inputCount))
52
+ inputTokens += itemTokens(item);
53
+ }
54
+ else {
55
+ inputTokens =
56
+ 32 +
57
+ (responses.instructions ? estimateStringTokens(responses.instructions) : 0) +
58
+ visibleTokens(tools.map((tool) => ({
59
+ name: tool.wireName,
60
+ description: tool.description,
61
+ parameters: tool.inputSchema,
62
+ })));
63
+ for (const [index, item] of items.entries()) {
64
+ inputTokens += itemTokens(item) + (opaqueReasoningBounds?.get(index) ?? 0);
65
+ if (item.type === 'reasoning' &&
66
+ typeof item.encrypted_content === 'string' &&
67
+ !opaqueReasoningBounds?.has(index))
68
+ throw new RuntimeError('UNESTIMABLE_CONTINUATION', '原生推理续接缺少可用的历史用量');
69
+ }
70
+ }
71
+ return { inputTokens, accuracy: 'conservative_estimate' };
72
+ },
73
+ };
@@ -0,0 +1,2 @@
1
+ import type { ToolBinding, ToolExecutionReader } from '@saturn-universe/core';
2
+ export declare function createToolResultReader(reader: ToolExecutionReader): ToolBinding;
@@ -0,0 +1,91 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ import { toolResultTextPage } from '@saturn-universe/context';
3
+ export function createToolResultReader(reader) {
4
+ return {
5
+ definition: {
6
+ name: 'read_tool_result',
7
+ version: '1',
8
+ description: 'Read the retained result for a completed tool call in this agent session. Defaults to plain text (4096 bytes per page, max 32768). Supports byte_offset, max_bytes, line_offset (0-based), line_count, case-insensitive query filtering, and format ("text" | "raw_json").',
9
+ inputSchema: {
10
+ type: 'object',
11
+ properties: {
12
+ tool_call_id: { type: 'string', minLength: 1, maxLength: 200 },
13
+ byte_offset: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER - 32768 },
14
+ max_bytes: { type: 'integer', minimum: 1, maximum: 32768 },
15
+ line_offset: { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER },
16
+ line_count: { type: 'integer', minimum: 1, maximum: 1000 },
17
+ query: { type: 'string', minLength: 1, maxLength: 256 },
18
+ format: { type: 'string', enum: ['text', 'raw_json'] },
19
+ },
20
+ required: ['tool_call_id'],
21
+ additionalProperties: false,
22
+ },
23
+ source: { kind: 'builtin' },
24
+ effects: 'read',
25
+ supportsIdempotencyKey: false,
26
+ supportsReconcile: false,
27
+ concurrency: 'parallel',
28
+ timeoutMs: 5000,
29
+ },
30
+ handler: {
31
+ async invoke(input, context) {
32
+ const { tool_call_id, byte_offset, max_bytes, line_offset, line_count, query, format } = input;
33
+ const call = await reader.read(tool_call_id).catch((error) => {
34
+ if (error instanceof RuntimeError && error.code === 'NOT_FOUND')
35
+ return undefined;
36
+ throw error;
37
+ });
38
+ context.signal.throwIfAborted();
39
+ if (!call?.result || call.agentSessionId !== context.agentSessionId || call.status !== 'settled')
40
+ return {
41
+ effect: 'none',
42
+ outcome: {
43
+ status: 'error',
44
+ error: {
45
+ code: 'NOT_FOUND',
46
+ message: 'No retained result for this tool_call_id',
47
+ retryable: false,
48
+ },
49
+ },
50
+ };
51
+ const page = toolResultTextPage(call.result.outcome, {
52
+ ...(byte_offset !== undefined ? { byteOffset: byte_offset } : {}),
53
+ ...(max_bytes !== undefined ? { maxBytes: max_bytes } : {}),
54
+ ...(line_offset !== undefined ? { lineOffset: line_offset } : {}),
55
+ ...(line_count !== undefined ? { lineCount: line_count } : {}),
56
+ ...(query !== undefined ? { query } : {}),
57
+ ...(format !== undefined ? { format } : {}),
58
+ });
59
+ if (!page)
60
+ return {
61
+ effect: 'none',
62
+ outcome: {
63
+ status: 'error',
64
+ error: {
65
+ code: 'INVALID_ARGUMENTS',
66
+ message: 'Offset is outside the selected result or splits a UTF-8 character',
67
+ retryable: false,
68
+ },
69
+ },
70
+ };
71
+ return {
72
+ effect: 'none',
73
+ outcome: {
74
+ status: 'success',
75
+ content: [{ type: 'text', text: page.text }],
76
+ data: {
77
+ next_byte_offset: page.nextByteOffset,
78
+ ...(page.nextWindowByteOffset !== undefined
79
+ ? { next_window_byte_offset: page.nextWindowByteOffset }
80
+ : {}),
81
+ ...(page.nextLineOffset !== undefined ? { next_line_offset: page.nextLineOffset } : {}),
82
+ total_bytes: page.totalBytes,
83
+ total_lines: page.totalLines,
84
+ ...(page.matchedLines !== undefined ? { matched_lines: page.matchedLines } : {}),
85
+ },
86
+ },
87
+ };
88
+ },
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ export declare const webSearchProviders: readonly ["tavily", "brave", "serper", "exa", "custom"];
3
+ export declare const maxWebSearchResults = 10;
4
+ export declare const maxWebFetchChars = 40000;
5
+ export declare const webSearchConfig: z.ZodObject<{
6
+ enabled: z.ZodDefault<z.ZodBoolean>;
7
+ provider: z.ZodEnum<{
8
+ tavily: "tavily";
9
+ brave: "brave";
10
+ serper: "serper";
11
+ exa: "exa";
12
+ custom: "custom";
13
+ }>;
14
+ api_key_env: z.ZodOptional<z.ZodString>;
15
+ base_url: z.ZodOptional<z.ZodURL>;
16
+ default_max_results: z.ZodDefault<z.ZodNumber>;
17
+ timeout_ms: z.ZodDefault<z.ZodNumber>;
18
+ fetch_enabled: z.ZodDefault<z.ZodBoolean>;
19
+ fetch_max_chars: z.ZodDefault<z.ZodNumber>;
20
+ allow_fake_ip: z.ZodDefault<z.ZodBoolean>;
21
+ }, z.core.$strict>;
22
+ export type WebSearchConfig = z.output<typeof webSearchConfig>;
23
+ export declare function resolveWebSearchKey(config?: WebSearchConfig, env?: NodeJS.ProcessEnv | ReadonlyMap<string, string>): string | undefined;
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ export const webSearchProviders = ['tavily', 'brave', 'serper', 'exa', 'custom'];
3
+ export const maxWebSearchResults = 10;
4
+ export const maxWebFetchChars = 40_000;
5
+ export const webSearchConfig = z
6
+ .strictObject({
7
+ enabled: z.boolean().default(true),
8
+ provider: z.enum(webSearchProviders),
9
+ api_key_env: z
10
+ .string()
11
+ .regex(/^[a-zA-Z_][a-zA-Z0-9_]*$/)
12
+ .optional(),
13
+ base_url: z
14
+ .url({ protocol: /^https?$/ })
15
+ .refine((value) => {
16
+ const url = new URL(value);
17
+ return !url.username && !url.password && !url.hash;
18
+ })
19
+ .optional(),
20
+ default_max_results: z.number().int().min(1).max(maxWebSearchResults).default(5),
21
+ timeout_ms: z.number().int().min(1).max(60_000).default(15_000),
22
+ fetch_enabled: z.boolean().default(true),
23
+ fetch_max_chars: z.number().int().min(1).max(maxWebFetchChars).default(16_000),
24
+ allow_fake_ip: z.boolean().default(true),
25
+ })
26
+ .refine(({ provider, base_url }) => provider !== 'custom' || base_url !== undefined);
27
+ export function resolveWebSearchKey(config, env = process.env) {
28
+ if (!config?.enabled)
29
+ return;
30
+ const name = config.api_key_env ??
31
+ (config.provider === 'custom'
32
+ ? 'SATURN_CUSTOM_API_KEY'
33
+ : `SATURN_${config.provider.toUpperCase()}_API_KEY`);
34
+ const raw = env instanceof Map ? env.get(name) : env[name];
35
+ return raw?.trim() || undefined;
36
+ }