@dev-zero/mcp-agent 0.0.3 → 0.0.4
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/README.md +2 -2
- package/package.json +1 -1
- package/src/local-mcp-client.mjs +10 -3
- package/src/local-mcp-server.mjs +5 -2
- package/src/main.mjs +5 -2
- package/src/tools/pc-tools.mjs +226 -0
- package/src/worker.mjs +29 -9
package/README.md
CHANGED
|
@@ -69,7 +69,7 @@ unverified acceptance gates.
|
|
|
69
69
|
|
|
70
70
|
## Publishing with EOTP on MiruZero
|
|
71
71
|
|
|
72
|
-
The Agent's **source-only** release helper follows the validated `M:\\Zero_ChatGPT` release workflow. It calls the installed `
|
|
72
|
+
The Agent's **source-only** release helper follows the validated `M:\\Zero_ChatGPT` release workflow. It calls the installed `zero eotp npm --json`, passes the resulting 6-digit TOTP only to the child npm process through `npm_config_otp`, and never logs or stores the code. The helper is excluded from the published Agent tarball.
|
|
73
73
|
|
|
74
74
|
```powershell
|
|
75
75
|
Set-Location M:\\Zero_SERVER\\source\\agent\\zero-agent
|
|
@@ -77,6 +77,6 @@ npm run release:eotp:check # Tests, pack audit, public-registry version che
|
|
|
77
77
|
npm run release:eotp # Verify npm login, obtain new EOTP, publish, verify registry
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
This needs a **normal online PowerShell session** running as the Windows user who configured `
|
|
80
|
+
This needs a **normal online PowerShell session** running as the Windows user who configured `zero eotp npm`; the Remote Desktop Commander execution environment may enforce `npm_config_offline=true` and cannot perform npm registry mutations. The helper reports `NPM_OFFLINE_ENV` without attempting a false publish in that environment. The npm account token needs permission to publish `@dev-zero/mcp-agent`; possessing a valid OTP alone does not grant package permissions. An OTP error (`EOTP`) is distinct from Registry HTTP404 (version absent, permissions, or package access). A release is VERIFIED only when the registry serves the exact published version; no automatic version bump, process restart, or npm global install occurs.
|
|
81
81
|
|
|
82
82
|
**Publish metadata:** `@dev-zero/mcp-agent` is configured for public npm distribution with `publishConfig.access=public`. Packaging readiness is not proof of a successful registry publication. Project runtime and credentials remain on the local machine; do not include them in an npm archive.
|
package/package.json
CHANGED
package/src/local-mcp-client.mjs
CHANGED
|
@@ -2,8 +2,10 @@ import {fileURLToPath} from 'node:url';
|
|
|
2
2
|
import {Client} from '@modelcontextprotocol/client';
|
|
3
3
|
import {StdioClientTransport} from '@modelcontextprotocol/client/stdio';
|
|
4
4
|
import {sandboxFileNames} from './tools/sandbox-files.mjs';
|
|
5
|
+
import {pcToolNames} from './tools/pc-tools.mjs';
|
|
5
6
|
export async function connectLocalMcp(){
|
|
6
|
-
const
|
|
7
|
+
const filesEnabled=process.env.ZERO_AGENT_FILE_TOOLS==='1';
|
|
8
|
+
const pcEnabled=process.env.ZERO_AGENT_PC_TOOLS==='1';
|
|
7
9
|
const serverFile=fileURLToPath(new URL('./local-mcp-server.mjs',import.meta.url));
|
|
8
10
|
const transport=new StdioClientTransport({
|
|
9
11
|
command:process.execPath,args:[serverFile],stderr:'pipe',
|
|
@@ -14,13 +16,18 @@ export async function connectLocalMcp(){
|
|
|
14
16
|
await client.connect(transport);
|
|
15
17
|
const catalog=(await client.listTools()).tools??[];
|
|
16
18
|
const actual=catalog.map(t=>t.name).sort();
|
|
17
|
-
const expected=
|
|
19
|
+
const expected=[
|
|
20
|
+
...(filesEnabled?sandboxFileNames:[]),
|
|
21
|
+
...(pcEnabled?pcToolNames:[])
|
|
22
|
+
].sort();
|
|
18
23
|
if(JSON.stringify(actual)!==JSON.stringify(expected))throw new Error('LOCAL_MCP_UNEXPECTED_TOOL');
|
|
19
24
|
}catch(error){await client.close().catch(()=>{});throw error}
|
|
20
25
|
return {
|
|
21
26
|
listTools:async()=>((await client.listTools()).tools??[]),
|
|
22
27
|
execute:async({name,arguments:args})=>{
|
|
23
|
-
|
|
28
|
+
const allowed=(filesEnabled&&sandboxFileNames.includes(name))||
|
|
29
|
+
(pcEnabled&&pcToolNames.includes(name));
|
|
30
|
+
if(!allowed)throw new Error('LOCAL_MCP_TOOL_DENIED');
|
|
24
31
|
return client.callTool({name,arguments:args});
|
|
25
32
|
},
|
|
26
33
|
close:()=>client.close()
|
package/src/local-mcp-server.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import {McpServer} from '@modelcontextprotocol/server';
|
|
|
2
2
|
import {StdioServerTransport} from '@modelcontextprotocol/server/stdio';
|
|
3
3
|
import {z} from 'zod';
|
|
4
4
|
import {createSandboxFileTools} from './tools/sandbox-files.mjs';
|
|
5
|
-
|
|
5
|
+
import {registerPcTools} from './tools/pc-tools.mjs';
|
|
6
|
+
const server=new McpServer({name:'zero-server-agent-local',version:'0.0.4'});
|
|
6
7
|
if(process.env.ZERO_AGENT_FILE_TOOLS==='1'){
|
|
7
8
|
const ops=createSandboxFileTools({root:process.env.ZERO_FILE_TOOL_ROOT});
|
|
8
9
|
const name=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}\.txt$/);
|
|
@@ -24,7 +25,9 @@ if(process.env.ZERO_AGENT_FILE_TOOLS==='1'){
|
|
|
24
25
|
z.object({name,old_text:small,new_text:small,expected_sha256:hash}),args=>ops.edit(args));
|
|
25
26
|
register('zero.files.delete','Delete a sandbox text file only with confirm=true and matching SHA-256.',
|
|
26
27
|
z.object({name,expected_sha256:hash,confirm:z.literal(true)}),args=>ops.delete(args));
|
|
27
|
-
}
|
|
28
|
+
}
|
|
29
|
+
if(process.env.ZERO_AGENT_PC_TOOLS==='1')registerPcTools(server);
|
|
30
|
+
if(process.env.ZERO_AGENT_FILE_TOOLS!=='1'&&process.env.ZERO_AGENT_PC_TOOLS!=='1'){
|
|
28
31
|
// Previous Connect-only MCP catalog remains unchanged unless explicitly opt-in.
|
|
29
32
|
server.setToolRequestHandlers();
|
|
30
33
|
}
|
package/src/main.mjs
CHANGED
|
@@ -17,8 +17,11 @@ const serverUrl=process.env.ZERO_AGENT_GATEWAY_URL || gatewayUrl || 'http://127.
|
|
|
17
17
|
// readiness to Core; an Agent heartbeat alone is not local tool readiness.
|
|
18
18
|
const localMcp=await connectLocalMcp();
|
|
19
19
|
const localTools=await localMcp.listTools();
|
|
20
|
-
const capabilities=localTools.map(tool=>({
|
|
21
|
-
|
|
20
|
+
const capabilities=localTools.map(tool=>({
|
|
21
|
+
name:tool.name,
|
|
22
|
+
description:tool.description,
|
|
23
|
+
inputSchema:tool.inputSchema
|
|
24
|
+
}));
|
|
22
25
|
let capabilitySynced=false;
|
|
23
26
|
async function publishCapabilities(){
|
|
24
27
|
const response=await fetch(new URL('/agent/capabilities',serverUrl),{
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {spawn} from 'node:child_process';
|
|
3
|
+
import {mkdir,readFile,readdir,realpath,rm,stat,writeFile} from 'node:fs/promises';
|
|
4
|
+
import {existsSync} from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import {z} from 'zod';
|
|
8
|
+
|
|
9
|
+
const pathArg=z.string().min(1);
|
|
10
|
+
const schemas={
|
|
11
|
+
pc_system_info:z.object({}),
|
|
12
|
+
pc_run_powershell:z.object({
|
|
13
|
+
command:z.string().min(1).max(8000),
|
|
14
|
+
cwd:pathArg.optional(),
|
|
15
|
+
timeoutMs:z.number().int().min(1000).max(600000).optional()
|
|
16
|
+
}).strict(),
|
|
17
|
+
pc_list_dir:z.object({path:pathArg,limit:z.number().int().min(1).max(1000).optional()}).strict(),
|
|
18
|
+
pc_read_file:z.object({path:pathArg,maxBytes:z.number().int().min(1).max(1000000).optional()}).strict(),
|
|
19
|
+
pc_write_file:z.object({path:pathArg,content:z.string().max(1000000),append:z.boolean().optional()}).strict(),
|
|
20
|
+
pc_open:z.object({target:z.string().min(1).max(2048)}).strict(),
|
|
21
|
+
pc_list_processes:z.object({
|
|
22
|
+
limit:z.number().int().min(1).max(200).optional(),
|
|
23
|
+
nameFilter:z.string().min(1).max(128).optional()
|
|
24
|
+
}).strict(),
|
|
25
|
+
pc_screenshot:z.object({maxWidth:z.number().int().min(320).max(3840).optional()}).strict(),
|
|
26
|
+
pc_clipboard_get:z.object({}),
|
|
27
|
+
pc_clipboard_set:z.object({text:z.string().max(100000)}).strict()
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const pcToolNames=Object.freeze(Object.keys(schemas));
|
|
31
|
+
export const pcToolDescriptions=Object.freeze({
|
|
32
|
+
pc_system_info:'Report hostname, OS version, uptime, CPU, memory and disk usage of the Windows PC.',
|
|
33
|
+
pc_run_powershell:'Run an explicitly authorized PowerShell command on the Windows PC.',
|
|
34
|
+
pc_list_dir:'List entries of an allowed directory on the Windows PC.',
|
|
35
|
+
pc_read_file:'Read a UTF-8 text file from an allowed Windows path.',
|
|
36
|
+
pc_write_file:'Create, overwrite or append a UTF-8 text file under an allowed Windows root.',
|
|
37
|
+
pc_open:'Open an allowed file/folder or an http(s) URL with its default application.',
|
|
38
|
+
pc_list_processes:'List top Windows processes by memory use.',
|
|
39
|
+
pc_screenshot:'Capture the primary Windows screen as PNG.',
|
|
40
|
+
pc_clipboard_get:'Read text currently on the Windows clipboard.',
|
|
41
|
+
pc_clipboard_set:'Write text to the Windows clipboard.'
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const textResult=(text,isError=false)=>({content:[{type:'text',text}],...(isError?{isError:true}:{})});
|
|
45
|
+
const json=value=>textResult(JSON.stringify(value,null,2));
|
|
46
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
47
|
+
const quote=value=>"'"+String(value).replaceAll("'","''")+"'";
|
|
48
|
+
|
|
49
|
+
function rootsFrom(env){
|
|
50
|
+
return String(env.ZERO_PC_ALLOWED_ROOTS??'').split(';').map(x=>x.trim()).filter(Boolean).map(x=>path.resolve(x));
|
|
51
|
+
}
|
|
52
|
+
function inside(target,root){
|
|
53
|
+
const rel=path.relative(root,target);
|
|
54
|
+
return rel===''||(!rel.startsWith('..'+path.sep)&&rel!=='..'&&!path.isAbsolute(rel));
|
|
55
|
+
}
|
|
56
|
+
async function canonicalAllowed(input,{roots,write=false}={}){
|
|
57
|
+
if(!roots?.length)throw fail('PC_PATH_ROOTS_REQUIRED');
|
|
58
|
+
const resolved=path.resolve(input);
|
|
59
|
+
const lexical=roots.find(root=>inside(resolved,root));
|
|
60
|
+
if(!lexical)throw fail('PC_PATH_DENIED');
|
|
61
|
+
let rootReal;
|
|
62
|
+
try{rootReal=await realpath(lexical)}catch{throw fail('PC_PATH_ROOT_INVALID')}
|
|
63
|
+
if(!write){
|
|
64
|
+
let targetReal;
|
|
65
|
+
try{targetReal=await realpath(resolved)}catch{throw fail('PC_PATH_NOT_FOUND')}
|
|
66
|
+
if(!inside(targetReal,rootReal))throw fail('PC_PATH_DENIED');
|
|
67
|
+
return targetReal;
|
|
68
|
+
}
|
|
69
|
+
let probe=path.dirname(resolved);
|
|
70
|
+
while(!existsSync(probe)){
|
|
71
|
+
const parent=path.dirname(probe);
|
|
72
|
+
if(parent===probe)throw fail('PC_PATH_DENIED');
|
|
73
|
+
probe=parent;
|
|
74
|
+
}
|
|
75
|
+
const parentReal=await realpath(probe);
|
|
76
|
+
if(!inside(parentReal,rootReal))throw fail('PC_PATH_DENIED');
|
|
77
|
+
return resolved;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function runner({env=process.env}={}){
|
|
81
|
+
const executable=env.POWERSHELL_EXE??'powershell.exe';
|
|
82
|
+
const maxChars=Math.min(200000,Math.max(1000,Number(env.ZERO_PC_MAX_OUTPUT_CHARS??60000)||60000));
|
|
83
|
+
const defaultTimeout=Math.min(600000,Math.max(1000,Number(env.ZERO_PC_TIMEOUT_MS??60000)||60000));
|
|
84
|
+
const workingDir=env.ZERO_PC_CWD?path.resolve(env.ZERO_PC_CWD):process.cwd();
|
|
85
|
+
const clamp=value=>value.length<=maxChars?value:
|
|
86
|
+
value.slice(0,maxChars)+'\n...[truncated, '+(value.length-maxChars)+' more characters]';
|
|
87
|
+
const run=(command,{cwd,timeoutMs}={})=>new Promise(resolve=>{
|
|
88
|
+
const child=spawn(executable,['-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-Command',command],
|
|
89
|
+
{cwd:cwd??workingDir,windowsHide:true});
|
|
90
|
+
let stdout='',stderr='',timedOut=false,settled=false;
|
|
91
|
+
const timer=setTimeout(()=>{timedOut=true;child.kill()},timeoutMs??defaultTimeout);
|
|
92
|
+
child.stdout?.setEncoding('utf8');child.stderr?.setEncoding('utf8');
|
|
93
|
+
child.stdout?.on('data',chunk=>{if(stdout.length<maxChars*2)stdout+=chunk});
|
|
94
|
+
child.stderr?.on('data',chunk=>{if(stderr.length<maxChars*2)stderr+=chunk});
|
|
95
|
+
const done=exitCode=>{if(settled)return;settled=true;clearTimeout(timer);
|
|
96
|
+
resolve({stdout:clamp(stdout),stderr:clamp(stderr),exitCode,timedOut})};
|
|
97
|
+
child.once('error',error=>{stderr+='\nFailed to start '+executable+': '+error.message;done(null)});
|
|
98
|
+
child.once('close',done);
|
|
99
|
+
});
|
|
100
|
+
const runJson=async(command,options)=>{
|
|
101
|
+
const out=await run(command,options);
|
|
102
|
+
if(out.timedOut)throw fail('PC_POWERSHELL_TIMEOUT');
|
|
103
|
+
if(out.exitCode!==0)throw fail('PC_POWERSHELL_FAILED');
|
|
104
|
+
try{return JSON.parse(out.stdout.trim())}catch{throw fail('PC_POWERSHELL_JSON_INVALID')}
|
|
105
|
+
};
|
|
106
|
+
return {run,runJson};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function pcToolSchemas(){return schemas}
|
|
110
|
+
|
|
111
|
+
export function registerPcTools(server,{env=process.env}={}){
|
|
112
|
+
const roots=rootsFrom(env),controlEnabled=env.ZERO_PC_CONTROL_ENABLED==='1';
|
|
113
|
+
const {run,runJson}=runner({env});
|
|
114
|
+
const execute=async(name,args)=>{
|
|
115
|
+
const parsed=schemas[name]?.safeParse(args??{});
|
|
116
|
+
if(!parsed?.success)return textResult('PC_TOOL_INPUT_INVALID',true);
|
|
117
|
+
try{
|
|
118
|
+
switch(name){
|
|
119
|
+
case 'pc_system_info':{
|
|
120
|
+
const info=await runJson(
|
|
121
|
+
'$os=Get-CimInstance Win32_OperatingSystem;'+
|
|
122
|
+
'$cpu=Get-CimInstance Win32_Processor|Select-Object -First 1;'+
|
|
123
|
+
'$disks=Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"|ForEach-Object {'+
|
|
124
|
+
'[pscustomobject]@{drive=$_.DeviceID;totalGB=[math]::Round($_.Size/1GB,1);freeGB=[math]::Round($_.FreeSpace/1GB,1)}};'+
|
|
125
|
+
'[pscustomobject]@{hostname=$env:COMPUTERNAME;os=$os.Caption;osVersion=$os.Version;osBuild=$os.BuildNumber;'+
|
|
126
|
+
'lastBootUpTime=$os.LastBootUpTime.ToString("o");cpu=$cpu.Name;cpuCores=$cpu.NumberOfCores;'+
|
|
127
|
+
'cpuLogical=$cpu.NumberOfLogicalProcessors;memoryTotalGB=[math]::Round($os.TotalVisibleMemorySize/1MB,1);'+
|
|
128
|
+
'memoryFreeGB=[math]::Round($os.FreePhysicalMemory/1MB,1);disks=@($disks)}|ConvertTo-Json -Depth 4 -Compress'
|
|
129
|
+
);
|
|
130
|
+
return json({...info,agentUptimeSeconds:Math.round(process.uptime()),nodeVersion:process.version});
|
|
131
|
+
}
|
|
132
|
+
case 'pc_run_powershell':{
|
|
133
|
+
if(!controlEnabled)return textResult('PC_CONTROL_DISABLED',true);
|
|
134
|
+
const {command,cwd,timeoutMs}=parsed.data;
|
|
135
|
+
const out=await run(command,{cwd:cwd?await canonicalAllowed(cwd,{roots}):undefined,timeoutMs});
|
|
136
|
+
const parts=['exitCode: '+(out.timedOut?'timed out':out.exitCode),
|
|
137
|
+
out.stdout.trim()?'stdout:\n'+out.stdout.trimEnd():'stdout: (empty)'];
|
|
138
|
+
if(out.stderr.trim())parts.push('stderr:\n'+out.stderr.trimEnd());
|
|
139
|
+
return textResult(parts.join('\n\n'),out.timedOut||(out.exitCode??1)!==0);
|
|
140
|
+
}
|
|
141
|
+
case 'pc_list_dir':{
|
|
142
|
+
const dir=await canonicalAllowed(parsed.data.path,{roots});
|
|
143
|
+
const entries=await readdir(dir,{withFileTypes:true});
|
|
144
|
+
const rows=await Promise.all(entries.slice(0,parsed.data.limit??200).map(async entry=>{
|
|
145
|
+
const full=path.join(dir,entry.name);
|
|
146
|
+
try{const s=await stat(full);return {name:entry.name,
|
|
147
|
+
type:entry.isDirectory()?'dir':entry.isFile()?'file':'other',
|
|
148
|
+
...(entry.isFile()?{sizeBytes:s.size}:{}),modified:s.mtime.toISOString()}}
|
|
149
|
+
catch{return {name:entry.name,type:'unreadable'}}
|
|
150
|
+
}));
|
|
151
|
+
return json({path:dir,totalEntries:entries.length,returned:rows.length,entries:rows});
|
|
152
|
+
}
|
|
153
|
+
case 'pc_read_file':{
|
|
154
|
+
const file=await canonicalAllowed(parsed.data.path,{roots});
|
|
155
|
+
const s=await stat(file);if(!s.isFile())throw fail('PC_PATH_NOT_FILE');
|
|
156
|
+
const buffer=await readFile(file),max=parsed.data.maxBytes??200000,slice=buffer.subarray(0,max);
|
|
157
|
+
return textResult('path: '+file+'\nsizeBytes: '+s.size+
|
|
158
|
+
(buffer.length>slice.length?' (showing first '+max+' bytes)':'')+'\n---\n'+slice.toString('utf8'));
|
|
159
|
+
}
|
|
160
|
+
case 'pc_write_file':{
|
|
161
|
+
if(!controlEnabled)return textResult('PC_CONTROL_DISABLED',true);
|
|
162
|
+
const file=await canonicalAllowed(parsed.data.path,{roots,write:true});
|
|
163
|
+
await mkdir(path.dirname(file),{recursive:true});
|
|
164
|
+
await writeFile(file,parsed.data.content,{encoding:'utf8',flag:parsed.data.append?'a':'w'});
|
|
165
|
+
const s=await stat(file);
|
|
166
|
+
return textResult((parsed.data.append?'Appended to ':'Wrote ')+file+' ('+s.size+' bytes on disk).');
|
|
167
|
+
}
|
|
168
|
+
case 'pc_open':{
|
|
169
|
+
if(!controlEnabled)return textResult('PC_CONTROL_DISABLED',true);
|
|
170
|
+
const target=/^https?:\/\//i.test(parsed.data.target)?parsed.data.target:
|
|
171
|
+
await canonicalAllowed(parsed.data.target,{roots});
|
|
172
|
+
const out=await run('Start-Process '+quote(target),{timeoutMs:20000});
|
|
173
|
+
if(out.timedOut||out.exitCode!==0)return textResult('PC_OPEN_FAILED',true);
|
|
174
|
+
return textResult('Opened '+target+' with its default application.');
|
|
175
|
+
}
|
|
176
|
+
case 'pc_list_processes':{
|
|
177
|
+
const {limit=20,nameFilter}=parsed.data;
|
|
178
|
+
const filter=nameFilter?'| Where-Object { $_.ProcessName -like '+quote('*'+nameFilter+'*')+' } ':'';
|
|
179
|
+
const processes=await runJson('@(Get-Process '+filter+
|
|
180
|
+
'| Sort-Object WorkingSet64 -Descending | Select-Object -First '+limit+
|
|
181
|
+
' | ForEach-Object { [pscustomobject]@{name=$_.ProcessName;id=$_.Id;memoryMB=[math]::Round($_.WorkingSet64/1MB,1);'+
|
|
182
|
+
'cpuSeconds=[math]::Round($_.CPU,1)}})|ConvertTo-Json -Depth 3 -Compress');
|
|
183
|
+
return json({limit,nameFilter,processes});
|
|
184
|
+
}
|
|
185
|
+
case 'pc_screenshot':{
|
|
186
|
+
const maxWidth=parsed.data.maxWidth??1280,file=path.join(os.tmpdir(),'zero-pc-'+randomUUID()+'.png');
|
|
187
|
+
const script=['Add-Type -AssemblyName System.Windows.Forms, System.Drawing;',
|
|
188
|
+
'$b=[System.Windows.Forms.Screen]::PrimaryScreen.Bounds;',
|
|
189
|
+
'$shot=New-Object System.Drawing.Bitmap $b.Width,$b.Height;',
|
|
190
|
+
'$g=[System.Drawing.Graphics]::FromImage($shot);$g.CopyFromScreen($b.X,$b.Y,0,0,$shot.Size);',
|
|
191
|
+
'$maxW='+maxWidth+';',
|
|
192
|
+
'if($shot.Width -gt $maxW){$h=[int]($shot.Height*$maxW/$shot.Width);$r=New-Object System.Drawing.Bitmap $maxW,$h;'+
|
|
193
|
+
'$rg=[System.Drawing.Graphics]::FromImage($r);$rg.InterpolationMode=[System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic;'+
|
|
194
|
+
'$rg.DrawImage($shot,0,0,$maxW,$h);$rg.Dispose();$g.Dispose();$shot.Dispose();$shot=$r}else{$g.Dispose()};',
|
|
195
|
+
'$shot.Save('+quote(file)+',[System.Drawing.Imaging.ImageFormat]::Png);',
|
|
196
|
+
'$o=[pscustomobject]@{width=$shot.Width;height=$shot.Height};$shot.Dispose();$o|ConvertTo-Json -Compress'
|
|
197
|
+
].join(' ');
|
|
198
|
+
try{
|
|
199
|
+
const size=await runJson(script,{timeoutMs:60000}),png=await readFile(file);
|
|
200
|
+
if(png.length>4*1024*1024)throw fail('PC_SCREENSHOT_TOO_LARGE');
|
|
201
|
+
return {content:[{type:'text',text:'Screenshot of primary screen, '+size.width+'x'+size.height+' px.'},
|
|
202
|
+
{type:'image',data:png.toString('base64'),mimeType:'image/png'}]};
|
|
203
|
+
}finally{await rm(file,{force:true}).catch(()=>{})}
|
|
204
|
+
}
|
|
205
|
+
case 'pc_clipboard_get':{
|
|
206
|
+
const out=await run('Get-Clipboard -Raw',{timeoutMs:20000});
|
|
207
|
+
if(out.exitCode!==0)return textResult('PC_CLIPBOARD_READ_FAILED',true);
|
|
208
|
+
const value=out.stdout.replace(/\r?\n$/,'');
|
|
209
|
+
return textResult(value?'Clipboard text:\n'+value:'The clipboard holds no text.');
|
|
210
|
+
}
|
|
211
|
+
case 'pc_clipboard_set':{
|
|
212
|
+
if(!controlEnabled)return textResult('PC_CONTROL_DISABLED',true);
|
|
213
|
+
const out=await run('Set-Clipboard -Value '+quote(parsed.data.text),{timeoutMs:20000});
|
|
214
|
+
if(out.exitCode!==0)return textResult('PC_CLIPBOARD_WRITE_FAILED',true);
|
|
215
|
+
return textResult('Copied '+parsed.data.text.length+' characters to the clipboard.');
|
|
216
|
+
}
|
|
217
|
+
default:throw fail('PC_TOOL_NOT_FOUND');
|
|
218
|
+
}
|
|
219
|
+
}catch(error){return textResult(String(error?.code||error?.message||'PC_TOOL_FAILED'),true)}
|
|
220
|
+
};
|
|
221
|
+
for(const name of pcToolNames){
|
|
222
|
+
server.registerTool(name,{description:pcToolDescriptions[name],inputSchema:schemas[name]},
|
|
223
|
+
args=>execute(name,args));
|
|
224
|
+
}
|
|
225
|
+
return pcToolNames;
|
|
226
|
+
}
|
package/src/worker.mjs
CHANGED
|
@@ -1,29 +1,49 @@
|
|
|
1
|
+
import {hostname,platform,release,arch,type} from 'node:os';
|
|
2
|
+
import {readFileSync} from 'node:fs';
|
|
1
3
|
import {validateAgentGateway} from './gateway-url.mjs';
|
|
4
|
+
import {pcToolNames} from './tools/pc-tools.mjs';
|
|
5
|
+
import {sandboxFileNames} from './tools/sandbox-files.mjs';
|
|
6
|
+
|
|
7
|
+
const agentVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
8
|
+
export function localDeviceProfile(){
|
|
9
|
+
return {
|
|
10
|
+
device_name:hostname(),platform:platform(),os_type:type(),os_release:release(),
|
|
11
|
+
arch:arch(),agent_version:agentVersion,runtime_name:'node',runtime_version:process.version
|
|
12
|
+
};
|
|
13
|
+
}
|
|
2
14
|
|
|
3
15
|
// Connection, authenticated heartbeat and outbound channel are control-plane
|
|
4
16
|
// operations. The clean Agent has no authorized tool actions yet.
|
|
5
|
-
export async function runAgentOnce({serverUrl,agentId,secret,executeLocal}={}) {
|
|
17
|
+
export async function runAgentOnce({serverUrl,agentId,secret,executeLocal,deviceName,deviceProfile}={}) {
|
|
6
18
|
if(!/^https?:\/\//.test(serverUrl||'')||!agentId||!secret)throw new Error('AGENT_CONFIG_REQUIRED');
|
|
7
19
|
if(typeof executeLocal!=='function')throw new Error('LOCAL_MCP_REQUIRED');
|
|
20
|
+
const profile=deviceProfile??{...localDeviceProfile(),
|
|
21
|
+
...(deviceName!==undefined?{device_name:deviceName}:{})};
|
|
8
22
|
const base=validateAgentGateway(serverUrl);
|
|
9
23
|
const headers={'x-zero-agent-id':agentId,Authorization:'Bearer '+secret};
|
|
10
|
-
const hb=await fetch(new URL('/agent/heartbeat',base),{method:'POST',
|
|
24
|
+
const hb=await fetch(new URL('/agent/heartbeat',base),{method:'POST',
|
|
25
|
+
headers:{...headers,'content-type':'application/json'},
|
|
26
|
+
body:JSON.stringify({device_name:profile.device_name,device_profile:profile}),
|
|
27
|
+
redirect:'error',signal:AbortSignal.timeout(8000)});
|
|
11
28
|
if(hb.status!==204)throw new Error('AGENT_HEARTBEAT_FAILED_'+hb.status);
|
|
12
|
-
|
|
29
|
+
const filesEnabled=process.env.ZERO_AGENT_FILE_TOOLS==='1';
|
|
30
|
+
const pcEnabled=process.env.ZERO_AGENT_PC_TOOLS==='1';
|
|
31
|
+
if(!filesEnabled&&!pcEnabled)return {state:'idle'};
|
|
13
32
|
const next=await fetch(new URL('/agent/next',base),{headers,redirect:'error',signal:AbortSignal.timeout(8000)});
|
|
14
|
-
if(!next.ok)throw new Error('
|
|
33
|
+
if(!next.ok)throw new Error('AGENT_TOOL_LEASE_FAILED_'+next.status);
|
|
15
34
|
const lease=(await next.json()).task;
|
|
16
35
|
if(!lease)return {state:'idle'};
|
|
17
36
|
const job=lease.task;
|
|
18
|
-
|
|
19
|
-
|
|
37
|
+
const allowed=job&&((filesEnabled&&sandboxFileNames.includes(job.kind))||
|
|
38
|
+
(pcEnabled&&pcToolNames.includes(job.kind)));
|
|
39
|
+
if(!allowed)throw new Error('AGENT_TOOL_KIND_DENIED');
|
|
20
40
|
let output;
|
|
21
41
|
try {output=await executeLocal({name:job.kind,arguments:job.arguments});}
|
|
22
|
-
catch
|
|
42
|
+
catch{output={isError:true,content:[{type:'text',text:'TOOL_EXECUTION_FAILED'}]};}
|
|
23
43
|
const completed=await fetch(new URL('/agent/complete',base),{method:'POST',
|
|
24
44
|
headers:{...headers,'content-type':'application/json'},
|
|
25
45
|
body:JSON.stringify({task_id:job.task_id,lease_token:lease.lease_token,result:output}),
|
|
26
|
-
redirect:'error',signal:AbortSignal.timeout(
|
|
27
|
-
if(!completed.ok)throw new Error('
|
|
46
|
+
redirect:'error',signal:AbortSignal.timeout(15000)});
|
|
47
|
+
if(!completed.ok)throw new Error('AGENT_TOOL_COMPLETE_FAILED_'+completed.status);
|
|
28
48
|
return {state:'completed',task_id:job.task_id};
|
|
29
49
|
}
|