@saturn-universe/tools 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/container-sandbox.d.ts +168 -0
- package/dist/container-sandbox.js +1241 -0
- package/dist/counter.d.ts +5 -0
- package/dist/counter.js +82 -0
- package/dist/data-review.d.ts +4 -0
- package/dist/data-review.js +146 -0
- package/dist/execution-backend.d.ts +55 -0
- package/dist/execution-backend.js +339 -0
- package/dist/executor.d.ts +25 -0
- package/dist/executor.js +978 -0
- package/dist/file-window.d.ts +3 -0
- package/dist/file-window.js +12 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +17 -0
- package/dist/mcp-headers.d.ts +3 -0
- package/dist/mcp-headers.js +51 -0
- package/dist/mcp-http.d.ts +3 -0
- package/dist/mcp-http.js +253 -0
- package/dist/mcp-stdio.d.ts +2 -0
- package/dist/mcp-stdio.js +147 -0
- package/dist/mcp-wire.d.ts +33 -0
- package/dist/mcp-wire.js +85 -0
- package/dist/mcp.d.ts +19 -0
- package/dist/mcp.js +325 -0
- package/dist/path-containment.d.ts +3 -0
- package/dist/path-containment.js +11 -0
- package/dist/planner.d.ts +3 -0
- package/dist/planner.js +162 -0
- package/dist/process-manager.d.ts +67 -0
- package/dist/process-manager.js +423 -0
- package/dist/process-output.d.ts +34 -0
- package/dist/process-output.js +162 -0
- package/dist/process-worker.d.ts +1 -0
- package/dist/process-worker.js +202 -0
- package/dist/registry.d.ts +33 -0
- package/dist/registry.js +227 -0
- package/dist/search.d.ts +9 -0
- package/dist/search.js +96 -0
- package/dist/team.d.ts +36 -0
- package/dist/team.js +284 -0
- package/dist/text-patch.d.ts +15 -0
- package/dist/text-patch.js +81 -0
- package/dist/todo.d.ts +3 -0
- package/dist/todo.js +105 -0
- package/dist/workspace-discovery.d.ts +42 -0
- package/dist/workspace-discovery.js +404 -0
- package/dist/workspace-snapshot.d.ts +28 -0
- package/dist/workspace-snapshot.js +371 -0
- package/dist/workspace.d.ts +22 -0
- package/dist/workspace.js +1819 -0
- package/package.json +16 -3
- package/README.md +0 -3
package/dist/counter.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
export function createCounterTool(directory, options = {}) {
|
|
4
|
+
const filename = path.join(path.resolve(directory), 'effects.jsonl');
|
|
5
|
+
return {
|
|
6
|
+
definition: {
|
|
7
|
+
name: 'counter',
|
|
8
|
+
version: '1',
|
|
9
|
+
description: 'Append one controlled local counter increment',
|
|
10
|
+
inputSchema: {
|
|
11
|
+
type: 'object',
|
|
12
|
+
properties: { delta: { type: 'integer', minimum: 1, maximum: 100 } },
|
|
13
|
+
required: ['delta'],
|
|
14
|
+
additionalProperties: false,
|
|
15
|
+
},
|
|
16
|
+
source: { kind: 'builtin' },
|
|
17
|
+
effects: 'non_idempotent_write',
|
|
18
|
+
supportsIdempotencyKey: false,
|
|
19
|
+
supportsReconcile: options.reconcile ?? false,
|
|
20
|
+
concurrency: 'serial_per_run',
|
|
21
|
+
timeoutMs: 10000,
|
|
22
|
+
},
|
|
23
|
+
handler: {
|
|
24
|
+
async invoke(input, context) {
|
|
25
|
+
context.signal.throwIfAborted();
|
|
26
|
+
const delta = input.delta;
|
|
27
|
+
await mkdir(path.dirname(filename), { recursive: true });
|
|
28
|
+
await appendFile(filename, JSON.stringify({ executionKey: context.executionKey, delta }) + '\n', 'utf8');
|
|
29
|
+
if (options.holdAfterApply)
|
|
30
|
+
await new Promise((_, reject) => {
|
|
31
|
+
if (context.signal.aborted)
|
|
32
|
+
reject(context.signal.reason);
|
|
33
|
+
else
|
|
34
|
+
context.signal.addEventListener('abort', () => reject(context.signal.reason), { once: true });
|
|
35
|
+
});
|
|
36
|
+
return {
|
|
37
|
+
outcome: {
|
|
38
|
+
status: 'success',
|
|
39
|
+
content: [{ type: 'text', text: `Incremented by ${delta}` }],
|
|
40
|
+
data: { delta },
|
|
41
|
+
},
|
|
42
|
+
effect: 'applied',
|
|
43
|
+
evidenceRef: filename,
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
...(options.reconcile
|
|
47
|
+
? {
|
|
48
|
+
async reconcile(executionKey, context) {
|
|
49
|
+
const text = await readFile(filename, 'utf8').catch((error) => {
|
|
50
|
+
if (error.code === 'ENOENT')
|
|
51
|
+
return '';
|
|
52
|
+
throw error;
|
|
53
|
+
});
|
|
54
|
+
const record = text
|
|
55
|
+
.split('\n')
|
|
56
|
+
.filter(Boolean)
|
|
57
|
+
.map((line) => JSON.parse(line))
|
|
58
|
+
.find((record) => record.executionKey === executionKey);
|
|
59
|
+
if (!record)
|
|
60
|
+
return { kind: 'not_applied', evidenceRef: filename };
|
|
61
|
+
return {
|
|
62
|
+
kind: 'completed',
|
|
63
|
+
evidenceRef: filename,
|
|
64
|
+
result: {
|
|
65
|
+
toolCallId: context.executionKey
|
|
66
|
+
.split(':')
|
|
67
|
+
.at(-1),
|
|
68
|
+
outcome: {
|
|
69
|
+
status: 'success',
|
|
70
|
+
content: [{ type: 'text', text: `Incremented by ${record.delta}` }],
|
|
71
|
+
data: { delta: record.delta },
|
|
72
|
+
},
|
|
73
|
+
effect: 'applied',
|
|
74
|
+
evidenceRef: filename,
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
: {}),
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { RunId, ToolBinding } from '@saturn-universe/core';
|
|
2
|
+
export declare const dataReviewToolSet = "data-review";
|
|
3
|
+
export declare const dataReviewToolName = "review_numeric_data";
|
|
4
|
+
export declare function createDataReviewTool(previousReview?: (runId: RunId) => Promise<boolean>): ToolBinding;
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
export const dataReviewToolSet = 'data-review';
|
|
2
|
+
export const dataReviewToolName = 'review_numeric_data';
|
|
3
|
+
const checks = {
|
|
4
|
+
non_negative: (values) => values.filter((value) => value < 0).length,
|
|
5
|
+
integers: (values) => values.filter((value) => !Number.isInteger(value)).length,
|
|
6
|
+
unique: (values) => values.length - new Set(values).size,
|
|
7
|
+
};
|
|
8
|
+
const candidates = {
|
|
9
|
+
non_negative: {
|
|
10
|
+
clamp: (values) => values.map((value) => Math.max(0, value)),
|
|
11
|
+
remove_negative: (values) => values.filter((value) => value >= 0),
|
|
12
|
+
},
|
|
13
|
+
integers: {
|
|
14
|
+
round: (values) => values.map(Math.round),
|
|
15
|
+
truncate: (values) => values.map(Math.trunc),
|
|
16
|
+
},
|
|
17
|
+
unique: {
|
|
18
|
+
keep_first: (values) => [...new Set(values)],
|
|
19
|
+
keep_last: (values) => [...new Set([...values].reverse())].reverse(),
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
function isCheck(value) {
|
|
23
|
+
return typeof value === 'string' && Object.hasOwn(checks, value);
|
|
24
|
+
}
|
|
25
|
+
export function createDataReviewTool(previousReview) {
|
|
26
|
+
return {
|
|
27
|
+
definition: {
|
|
28
|
+
name: dataReviewToolName,
|
|
29
|
+
version: '1',
|
|
30
|
+
description: 'Check a numeric dataset against explicit rules and compare up to two rounds of fixed in-memory transformations. Returns the proposed data and audit trail. No files are written.',
|
|
31
|
+
inputSchema: {
|
|
32
|
+
type: 'object',
|
|
33
|
+
properties: {
|
|
34
|
+
values: { type: 'array', items: { type: 'number' }, maxItems: 2048 },
|
|
35
|
+
rules: {
|
|
36
|
+
type: 'array',
|
|
37
|
+
items: { type: 'string', enum: Object.keys(checks) },
|
|
38
|
+
minItems: 1,
|
|
39
|
+
maxItems: 3,
|
|
40
|
+
uniqueItems: true,
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
required: ['values', 'rules'],
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
},
|
|
46
|
+
source: { kind: 'builtin' },
|
|
47
|
+
effects: 'read',
|
|
48
|
+
supportsIdempotencyKey: false,
|
|
49
|
+
supportsReconcile: false,
|
|
50
|
+
concurrency: 'serial_per_run',
|
|
51
|
+
timeoutMs: 5000,
|
|
52
|
+
},
|
|
53
|
+
handler: {
|
|
54
|
+
async invoke(input, context) {
|
|
55
|
+
if (await previousReview?.(context.runId))
|
|
56
|
+
return {
|
|
57
|
+
effect: 'none',
|
|
58
|
+
outcome: {
|
|
59
|
+
status: 'error',
|
|
60
|
+
error: {
|
|
61
|
+
code: 'DATA_REVIEW_ALREADY_RECORDED',
|
|
62
|
+
message: 'Use the numeric review already recorded for this Run.',
|
|
63
|
+
retryable: false,
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
const values = input && typeof input === 'object' && 'values' in input ? input.values : undefined;
|
|
68
|
+
const rules = input && typeof input === 'object' && 'rules' in input ? input.rules : undefined;
|
|
69
|
+
if (!Array.isArray(values) ||
|
|
70
|
+
values.length > 2048 ||
|
|
71
|
+
!values.every((value) => typeof value === 'number' && Number.isFinite(value)) ||
|
|
72
|
+
!Array.isArray(rules) ||
|
|
73
|
+
rules.length < 1 ||
|
|
74
|
+
rules.length > 3 ||
|
|
75
|
+
!rules.every(isCheck) ||
|
|
76
|
+
new Set(rules).size !== rules.length) {
|
|
77
|
+
return {
|
|
78
|
+
effect: 'none',
|
|
79
|
+
outcome: {
|
|
80
|
+
status: 'error',
|
|
81
|
+
error: {
|
|
82
|
+
code: 'INVALID_DATA_REVIEW',
|
|
83
|
+
message: 'Expected finite numbers and one to three different checks.',
|
|
84
|
+
retryable: false,
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
const result = review(values, rules, context.signal);
|
|
90
|
+
return {
|
|
91
|
+
effect: 'none',
|
|
92
|
+
outcome: {
|
|
93
|
+
status: 'success',
|
|
94
|
+
content: [{ type: 'text', text: JSON.stringify(result) }],
|
|
95
|
+
data: result,
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function review(initial, rules, signal) {
|
|
103
|
+
const verify = (values) => rules.map((rule) => ({ rule, failures: checks[rule](values) }));
|
|
104
|
+
let values = initial;
|
|
105
|
+
let findings = verify(values);
|
|
106
|
+
const rounds = [];
|
|
107
|
+
const previous = new Set();
|
|
108
|
+
for (let index = 0; index < 2; index++) {
|
|
109
|
+
signal.throwIfAborted();
|
|
110
|
+
const evidence = findings.find(({ rule, failures }) => failures > 0 && !previous.has(rule));
|
|
111
|
+
if (!evidence)
|
|
112
|
+
break;
|
|
113
|
+
previous.add(evidence.rule);
|
|
114
|
+
const reports = Object.entries(candidates[evidence.rule]).map(([operation, transform]) => {
|
|
115
|
+
const proposed = transform(values);
|
|
116
|
+
const verified = verify(proposed);
|
|
117
|
+
return { operation, proposed, verified };
|
|
118
|
+
});
|
|
119
|
+
const acceptable = reports.filter(({ verified }) => verified.every(({ rule, failures }, position) => rule === evidence.rule ? failures < evidence.failures : failures <= findings[position].failures));
|
|
120
|
+
// Prefer retaining data among candidates that avoid regressing another acceptance check.
|
|
121
|
+
acceptable.sort((a, b) => b.proposed.length - a.proposed.length);
|
|
122
|
+
const selected = acceptable[0];
|
|
123
|
+
rounds.push({
|
|
124
|
+
round: index + 1,
|
|
125
|
+
evidence,
|
|
126
|
+
candidates: reports.map(({ operation, verified }) => ({ operation, checks: verified })),
|
|
127
|
+
selected: selected?.operation ?? null,
|
|
128
|
+
todos: (selected?.verified ?? findings).map(({ rule, failures }) => ({
|
|
129
|
+
id: rule,
|
|
130
|
+
content: `Verify ${rule}`,
|
|
131
|
+
status: failures === 0 ? 'completed' : 'pending',
|
|
132
|
+
})),
|
|
133
|
+
});
|
|
134
|
+
if (selected) {
|
|
135
|
+
values = selected.proposed;
|
|
136
|
+
findings = selected.verified;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
signal.throwIfAborted();
|
|
140
|
+
const todos = findings.map(({ rule, failures }) => ({
|
|
141
|
+
id: rule,
|
|
142
|
+
content: `Verify ${rule}`,
|
|
143
|
+
status: failures === 0 ? 'completed' : 'pending',
|
|
144
|
+
}));
|
|
145
|
+
return { kind: dataReviewToolName, values: [...values], checks: findings, rounds, todos };
|
|
146
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ChildProcess } from 'node:child_process';
|
|
2
|
+
import type { AgentSessionId, RunId, SandboxReadonlyMount, ToolObservation } from '@saturn-universe/core';
|
|
3
|
+
import type { ProcessStartInput } from './process-manager.js';
|
|
4
|
+
import type { ProcessOutput } from './process-output.js';
|
|
5
|
+
export interface ExecutionTarget {
|
|
6
|
+
readonly runId?: RunId;
|
|
7
|
+
readonly agentSessionId?: AgentSessionId;
|
|
8
|
+
}
|
|
9
|
+
export interface ExecCommandInput {
|
|
10
|
+
readonly program: string;
|
|
11
|
+
readonly args: readonly string[];
|
|
12
|
+
readonly cwd: string;
|
|
13
|
+
readonly stdin?: string;
|
|
14
|
+
readonly timeoutMs: number;
|
|
15
|
+
readonly signal: AbortSignal;
|
|
16
|
+
readonly output: ProcessOutput;
|
|
17
|
+
readonly effect: 'none' | 'applied';
|
|
18
|
+
}
|
|
19
|
+
export interface ResolvedExecutionContext {
|
|
20
|
+
readonly kind: 'host' | 'container';
|
|
21
|
+
readonly effectiveRoot: string;
|
|
22
|
+
readonly containerWorkDir?: string;
|
|
23
|
+
readonly readonly?: boolean;
|
|
24
|
+
readonly readonlyMounts?: readonly SandboxReadonlyMount[];
|
|
25
|
+
readonly containerId?: string;
|
|
26
|
+
readonly backend: ExecutionBackend;
|
|
27
|
+
}
|
|
28
|
+
export interface ExecutionBackend {
|
|
29
|
+
readonly kind: 'host' | 'container';
|
|
30
|
+
resolveContext(workingDirectory: string, target?: ExecutionTarget): ResolvedExecutionContext;
|
|
31
|
+
shellInvocation(command: string, target?: ExecutionTarget): {
|
|
32
|
+
readonly program: string;
|
|
33
|
+
readonly args: readonly string[];
|
|
34
|
+
};
|
|
35
|
+
runCommand(input: ExecCommandInput, target?: ExecutionTarget): Promise<ToolObservation>;
|
|
36
|
+
readContainerFile?(containerPath: string, offset: number, limit: number, signal: AbortSignal, target?: ExecutionTarget): Promise<{
|
|
37
|
+
readonly bytes: Buffer;
|
|
38
|
+
readonly more: boolean;
|
|
39
|
+
}>;
|
|
40
|
+
spawnRipgrep?(args: readonly string[], cwd: string, signal: AbortSignal, target?: ExecutionTarget): ChildProcess | undefined;
|
|
41
|
+
wrapStartProcess?(input: ProcessStartInput, target?: ExecutionTarget, executionKey?: string): ProcessStartInput;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Verifies every existing path segment from `canonicalRoot` to `candidatePath`
|
|
45
|
+
* remains strictly inside `canonicalRoot` without following symlinks outside.
|
|
46
|
+
*/
|
|
47
|
+
export declare function assertSandboxPathContained(canonicalRoot: string, candidatePath: string): Promise<string>;
|
|
48
|
+
export declare function computeDirectoryBytes(directory: string): Promise<number>;
|
|
49
|
+
export declare function hostShellInvocation(command: string): {
|
|
50
|
+
readonly program: string;
|
|
51
|
+
readonly args: readonly string[];
|
|
52
|
+
};
|
|
53
|
+
export declare function runBoundedHostProcess(program: string, args: readonly string[], cwd: string, signal: AbortSignal, effect: 'none' | 'applied', output: ProcessOutput, stdin?: string, timeoutMs?: number, env?: NodeJS.ProcessEnv): Promise<ToolObservation>;
|
|
54
|
+
export declare function terminateProcessTree(pid: number | undefined, program: string): Promise<boolean>;
|
|
55
|
+
export declare function createHostExecutionBackend(resolveHostRoot: (workingDirectory: string) => string): ExecutionBackend;
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { lstat, opendir, realpath } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
5
|
+
import { isContainedPath, relativePathWithin } from './path-containment.js';
|
|
6
|
+
import { processEnvironment } from './process-manager.js';
|
|
7
|
+
/**
|
|
8
|
+
* Verifies every existing path segment from `canonicalRoot` to `candidatePath`
|
|
9
|
+
* remains strictly inside `canonicalRoot` without following symlinks outside.
|
|
10
|
+
*/
|
|
11
|
+
export async function assertSandboxPathContained(canonicalRoot, candidatePath) {
|
|
12
|
+
const resolvedRoot = await realpath(canonicalRoot);
|
|
13
|
+
const resolvedCandidate = path.resolve(resolvedRoot, candidatePath);
|
|
14
|
+
const relative = relativePathWithin(resolvedRoot, resolvedCandidate);
|
|
15
|
+
if (relative === undefined) {
|
|
16
|
+
throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Path escapes sandbox work directory');
|
|
17
|
+
}
|
|
18
|
+
if (!relative)
|
|
19
|
+
return resolvedRoot;
|
|
20
|
+
const parts = relative.split(path.sep).filter(Boolean);
|
|
21
|
+
let current = resolvedRoot;
|
|
22
|
+
let canonicalParent = resolvedRoot;
|
|
23
|
+
for (let i = 0; i < parts.length; i++) {
|
|
24
|
+
const part = parts[i];
|
|
25
|
+
current = path.join(current, part);
|
|
26
|
+
let info;
|
|
27
|
+
try {
|
|
28
|
+
info = await lstat(current);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
if (error.code === 'ENOENT') {
|
|
32
|
+
return path.join(canonicalParent, ...parts.slice(i));
|
|
33
|
+
}
|
|
34
|
+
throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Path cannot be verified inside sandbox');
|
|
35
|
+
}
|
|
36
|
+
if (info.isSymbolicLink()) {
|
|
37
|
+
let realTarget;
|
|
38
|
+
try {
|
|
39
|
+
realTarget = await realpath(current);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
|
|
43
|
+
}
|
|
44
|
+
if (!isContainedPath(resolvedRoot, realTarget)) {
|
|
45
|
+
throw new RuntimeError('SANDBOX_SYMLINK_ESCAPE', 'Symlink escapes sandbox work directory');
|
|
46
|
+
}
|
|
47
|
+
canonicalParent = realTarget;
|
|
48
|
+
current = realTarget;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
canonicalParent = path.join(canonicalParent, part);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return canonicalParent;
|
|
55
|
+
}
|
|
56
|
+
export async function computeDirectoryBytes(directory) {
|
|
57
|
+
let total = 0;
|
|
58
|
+
const pending = [directory];
|
|
59
|
+
while (pending.length) {
|
|
60
|
+
const current = pending.pop();
|
|
61
|
+
let dir;
|
|
62
|
+
try {
|
|
63
|
+
dir = await opendir(current);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === 'ENOENT')
|
|
67
|
+
continue;
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
for await (const entry of dir) {
|
|
71
|
+
const fullPath = path.join(current, entry.name);
|
|
72
|
+
let info;
|
|
73
|
+
try {
|
|
74
|
+
info = await lstat(fullPath);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (info.isSymbolicLink())
|
|
80
|
+
continue;
|
|
81
|
+
if (info.isDirectory()) {
|
|
82
|
+
pending.push(fullPath);
|
|
83
|
+
}
|
|
84
|
+
else if (info.isFile()) {
|
|
85
|
+
total += info.size;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return total;
|
|
90
|
+
}
|
|
91
|
+
export function hostShellInvocation(command) {
|
|
92
|
+
if (process.platform === 'win32') {
|
|
93
|
+
const script = [
|
|
94
|
+
'$OutputEncoding = [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)',
|
|
95
|
+
command,
|
|
96
|
+
'if ($?) { exit 0 }; if ($LASTEXITCODE) { exit $LASTEXITCODE }; exit 1',
|
|
97
|
+
].join('\n');
|
|
98
|
+
return {
|
|
99
|
+
program: path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
100
|
+
args: [
|
|
101
|
+
'-NoLogo',
|
|
102
|
+
'-NoProfile',
|
|
103
|
+
'-NonInteractive',
|
|
104
|
+
'-EncodedCommand',
|
|
105
|
+
Buffer.from(script, 'utf16le').toString('base64'),
|
|
106
|
+
],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
return { program: '/bin/sh', args: ['-c', command] };
|
|
110
|
+
}
|
|
111
|
+
export async function runBoundedHostProcess(program, args, cwd, signal, effect, output, stdin, timeoutMs = 30_000, env = processEnvironment()) {
|
|
112
|
+
signal.throwIfAborted();
|
|
113
|
+
let child;
|
|
114
|
+
try {
|
|
115
|
+
child = spawn(program, [...args], {
|
|
116
|
+
cwd,
|
|
117
|
+
env,
|
|
118
|
+
shell: false,
|
|
119
|
+
windowsHide: true,
|
|
120
|
+
detached: process.platform !== 'win32',
|
|
121
|
+
stdio: stdin !== undefined ? ['pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'],
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
return {
|
|
126
|
+
outcome: {
|
|
127
|
+
status: 'error',
|
|
128
|
+
error: {
|
|
129
|
+
code: 'PROCESS_START_FAILED',
|
|
130
|
+
message: error instanceof Error ? error.message : String(error),
|
|
131
|
+
retryable: false,
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
effect: 'none',
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
return new Promise((resolve) => {
|
|
138
|
+
let launched = false;
|
|
139
|
+
let settled = false;
|
|
140
|
+
let stopping = false;
|
|
141
|
+
let closed = false;
|
|
142
|
+
let spillWrite;
|
|
143
|
+
const finish = async (observe) => {
|
|
144
|
+
if (settled)
|
|
145
|
+
return;
|
|
146
|
+
settled = true;
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
signal.removeEventListener('abort', abort);
|
|
149
|
+
await spillWrite;
|
|
150
|
+
resolve(observe(await output.finish()));
|
|
151
|
+
};
|
|
152
|
+
const collect = (stream) => (chunk) => {
|
|
153
|
+
const write = output.append(chunk, stream);
|
|
154
|
+
if (output.outputLimitExceeded)
|
|
155
|
+
stop('output_limit');
|
|
156
|
+
if (!write)
|
|
157
|
+
return;
|
|
158
|
+
child.stdout?.pause();
|
|
159
|
+
child.stderr?.pause();
|
|
160
|
+
spillWrite = write.then(() => {
|
|
161
|
+
if (output.outputLimitExceeded)
|
|
162
|
+
stop('output_limit');
|
|
163
|
+
child.stdout?.resume();
|
|
164
|
+
child.stderr?.resume();
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
const stop = (reason = 'timeout') => {
|
|
168
|
+
if (stopping || settled)
|
|
169
|
+
return;
|
|
170
|
+
stopping = true;
|
|
171
|
+
void (async () => {
|
|
172
|
+
const terminationConfirmed = await terminateProcessTree(child.pid, program);
|
|
173
|
+
if (!terminationConfirmed && child.exitCode === null && child.signalCode === null)
|
|
174
|
+
child.kill('SIGKILL');
|
|
175
|
+
for (let i = 0; i < 30 && !closed; i++)
|
|
176
|
+
await new Promise((done) => setTimeout(done, 10));
|
|
177
|
+
const confirmed = terminationConfirmed && (child.exitCode !== null || child.signalCode !== null);
|
|
178
|
+
child.stdin?.destroy();
|
|
179
|
+
child.stdout?.destroy();
|
|
180
|
+
child.stderr?.destroy();
|
|
181
|
+
const cancelled = signal.aborted && signal.reason?.name !== 'TimeoutError';
|
|
182
|
+
const outputLimit = reason === 'output_limit' || output.outputLimitExceeded;
|
|
183
|
+
void finish((capture) => ({
|
|
184
|
+
outcome: {
|
|
185
|
+
status: outputLimit ? 'error' : cancelled ? 'cancelled' : 'error',
|
|
186
|
+
error: {
|
|
187
|
+
code: outputLimit ? 'PROCESS_OUTPUT_LIMIT_EXCEEDED' : cancelled ? 'CANCELLED' : 'TIMEOUT',
|
|
188
|
+
message: confirmed
|
|
189
|
+
? `Process ${cancelled ? 'cancelled' : 'timed out'} and was terminated`
|
|
190
|
+
: `Process ${cancelled ? 'cancelled' : 'timed out'}; tree termination could not be confirmed`,
|
|
191
|
+
retryable: false,
|
|
192
|
+
},
|
|
193
|
+
data: {
|
|
194
|
+
...capture,
|
|
195
|
+
exitCode: child.exitCode,
|
|
196
|
+
signal: child.signalCode,
|
|
197
|
+
terminationConfirmed: confirmed,
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
effect: !launched ? 'none' : confirmed ? effect : 'unknown',
|
|
201
|
+
}));
|
|
202
|
+
})();
|
|
203
|
+
};
|
|
204
|
+
const abort = () => stop('timeout');
|
|
205
|
+
const timer = setTimeout(() => stop('timeout'), timeoutMs);
|
|
206
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
207
|
+
child.stdin?.on('error', () => {
|
|
208
|
+
// Ignore EPIPE when the child exits before consuming all stdin.
|
|
209
|
+
});
|
|
210
|
+
child.stdout?.on('data', collect(0));
|
|
211
|
+
child.stderr?.on('data', collect(1));
|
|
212
|
+
child.once('spawn', () => {
|
|
213
|
+
launched = true;
|
|
214
|
+
if (stdin !== undefined && child.stdin && !child.stdin.destroyed) {
|
|
215
|
+
child.stdin.end(stdin, 'utf8');
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
child.on('error', (error) => {
|
|
219
|
+
if (!launched)
|
|
220
|
+
void finish(() => ({
|
|
221
|
+
outcome: {
|
|
222
|
+
status: 'error',
|
|
223
|
+
error: { code: 'PROCESS_START_FAILED', message: error.message, retryable: false },
|
|
224
|
+
},
|
|
225
|
+
effect: 'none',
|
|
226
|
+
}));
|
|
227
|
+
});
|
|
228
|
+
child.once('close', (code, exitSignal) => {
|
|
229
|
+
closed = true;
|
|
230
|
+
if (!launched || stopping)
|
|
231
|
+
return;
|
|
232
|
+
void finish(({ stdout, stderr, ...capture }) => {
|
|
233
|
+
const data = { exitCode: code, signal: exitSignal, ...capture };
|
|
234
|
+
if (capture.spillLimitExceeded)
|
|
235
|
+
return {
|
|
236
|
+
effect,
|
|
237
|
+
outcome: {
|
|
238
|
+
status: 'error',
|
|
239
|
+
error: {
|
|
240
|
+
code: 'PROCESS_OUTPUT_LIMIT_EXCEEDED',
|
|
241
|
+
message: 'Process output spill limit exceeded',
|
|
242
|
+
retryable: false,
|
|
243
|
+
},
|
|
244
|
+
data: { ...data, stdout, stderr },
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
if (capture.spillError)
|
|
248
|
+
return {
|
|
249
|
+
effect,
|
|
250
|
+
outcome: {
|
|
251
|
+
status: 'error',
|
|
252
|
+
error: {
|
|
253
|
+
code: 'PROCESS_OUTPUT_SPILL_FAILED',
|
|
254
|
+
message: capture.spillError,
|
|
255
|
+
retryable: false,
|
|
256
|
+
},
|
|
257
|
+
data: { ...data, stdout, stderr },
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
const spill = capture.spillPath
|
|
261
|
+
? `\nOutput truncated (${capture.totalBytes} bytes, ${capture.totalLines} lines). Use read_file at ${capture.spillPath} for the bounded spill output.`
|
|
262
|
+
: '';
|
|
263
|
+
return {
|
|
264
|
+
outcome: {
|
|
265
|
+
status: 'success',
|
|
266
|
+
content: [
|
|
267
|
+
{
|
|
268
|
+
type: 'text',
|
|
269
|
+
text: `Process exit: ${code ?? exitSignal}${spill}\nstdout:\n${stdout}\nstderr:\n${stderr}`,
|
|
270
|
+
},
|
|
271
|
+
],
|
|
272
|
+
data,
|
|
273
|
+
},
|
|
274
|
+
effect,
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
export async function terminateProcessTree(pid, program) {
|
|
281
|
+
if (!pid)
|
|
282
|
+
return false;
|
|
283
|
+
if (process.platform === 'win32') {
|
|
284
|
+
const confirmed = await new Promise((resolve) => {
|
|
285
|
+
const killer = spawn(path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'taskkill.exe'), ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
286
|
+
const timer = setTimeout(() => {
|
|
287
|
+
killer.kill();
|
|
288
|
+
resolve(false);
|
|
289
|
+
}, 3000);
|
|
290
|
+
killer.once('error', () => {
|
|
291
|
+
clearTimeout(timer);
|
|
292
|
+
resolve(false);
|
|
293
|
+
});
|
|
294
|
+
killer.once('close', (code) => {
|
|
295
|
+
clearTimeout(timer);
|
|
296
|
+
resolve(code === 0);
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
return confirmed && path.basename(program).toLowerCase() !== 'wsl.exe';
|
|
300
|
+
}
|
|
301
|
+
const alive = () => {
|
|
302
|
+
try {
|
|
303
|
+
process.kill(-pid, 0);
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
return error.code !== 'ESRCH';
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
try {
|
|
311
|
+
process.kill(-pid, 'SIGKILL');
|
|
312
|
+
}
|
|
313
|
+
catch (error) {
|
|
314
|
+
if (error.code !== 'ESRCH')
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
for (let i = 0; i < 40 && alive(); i++)
|
|
318
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
319
|
+
return !alive();
|
|
320
|
+
}
|
|
321
|
+
export function createHostExecutionBackend(resolveHostRoot) {
|
|
322
|
+
const backend = {
|
|
323
|
+
kind: 'host',
|
|
324
|
+
resolveContext(workingDirectory) {
|
|
325
|
+
return {
|
|
326
|
+
kind: 'host',
|
|
327
|
+
effectiveRoot: resolveHostRoot(workingDirectory),
|
|
328
|
+
backend,
|
|
329
|
+
};
|
|
330
|
+
},
|
|
331
|
+
shellInvocation(command) {
|
|
332
|
+
return hostShellInvocation(command);
|
|
333
|
+
},
|
|
334
|
+
runCommand(input) {
|
|
335
|
+
return runBoundedHostProcess(input.program, input.args, input.cwd, input.signal, input.effect, input.output, input.stdin, input.timeoutMs);
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
return backend;
|
|
339
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { AgentSessionId, ArtifactReader, LoggerPort, ToolExecutor, ToolExecutionReader, ToolPermissionPolicy, ExecutionEnvironmentReader, ExecutionEnvironment, RuntimeStateReader, RuntimeJournal, RuntimeClock, Hash, ToolCallId, ToolApprovalDecision, ReconciliationDecision, CommandId, RunId, RunConfig, RuntimeHooks } from '@saturn-universe/core';
|
|
2
|
+
import type { Registry } from './registry.js';
|
|
3
|
+
export interface ExecutorDependencies {
|
|
4
|
+
logger: LoggerPort;
|
|
5
|
+
registry: Registry;
|
|
6
|
+
reader: ToolExecutionReader;
|
|
7
|
+
state: RuntimeStateReader;
|
|
8
|
+
environment: ExecutionEnvironmentReader;
|
|
9
|
+
artifactReader?: ArtifactReader;
|
|
10
|
+
journal: RuntimeJournal;
|
|
11
|
+
policy: ToolPermissionPolicy;
|
|
12
|
+
hooks?: (config: RunConfig, environment: ExecutionEnvironment) => RuntimeHooks;
|
|
13
|
+
isAgentIsolated?: (runId: RunId, agentSessionId: AgentSessionId) => boolean;
|
|
14
|
+
clock: RuntimeClock;
|
|
15
|
+
hash: Hash;
|
|
16
|
+
id(): string;
|
|
17
|
+
instanceId: string;
|
|
18
|
+
epoch: number;
|
|
19
|
+
}
|
|
20
|
+
export interface Executor extends ToolExecutor {
|
|
21
|
+
clearFileSnapshots(runId: RunId): void;
|
|
22
|
+
resolveApproval(decision: ToolApprovalDecision, commandId: CommandId, resume?: boolean): Promise<void>;
|
|
23
|
+
reconcile(callId: ToolCallId, decision: ReconciliationDecision, commandId: CommandId): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export declare function createToolExecutor(d: ExecutorDependencies): Executor;
|