@dev-zero/mcp-agent 0.0.2 → 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 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 `zgpt 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.
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 `zgpt 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.
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.
@@ -104,9 +104,12 @@ async function start(){
104
104
  console.log(' - ChatGPT session is not ready ('+reason+').');
105
105
  if(reason==='ambiguous')
106
106
  console.log(' - Multiple signed-in Chrome profiles found; use one ChatGPT account.');
107
- else
107
+ else if(reason==='browser_busy'){
108
+ console.log(' - Close all Chrome windows for a few seconds so Zero can verify this signed-in profile locally.');
109
+ console.log(' - Zero will not kill Chrome or extract browser cookies.');
110
+ }else
108
111
  console.log(' - Open Chrome, select or create your profile, and sign in at https://chatgpt.com/');
109
- console.log(' - Waiting for login with the same Device Code (no restart needed).');
112
+ console.log(' - Waiting with the same Device Code (no restart needed).');
110
113
  },
111
114
  onCode:({user_code,verification_uri_complete,expires_in})=>{
112
115
  console.log(' - 🔌 Connected to Remote MCP');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dev-zero/mcp-agent",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,7 +15,7 @@
15
15
  "start": "node bin/zero-agent.mjs remote",
16
16
  "status": "node bin/zero-agent.mjs status",
17
17
  "doctor": "node bin/zero-agent.mjs remote --help",
18
- "test": "node --test tests/*.test.mjs",
18
+ "test": "node --test --test-concurrency=1 tests/*.test.mjs",
19
19
  "packcheck": "npm pack --dry-run",
20
20
  "release:eotp": "node scripts/release-eotp.mjs",
21
21
  "release:eotp:check": "node scripts/release-eotp.mjs --check"
@@ -0,0 +1,121 @@
1
+ import {existsSync,readFileSync,readdirSync} from 'node:fs';
2
+ import {homedir} from 'node:os';
3
+ import {join} from 'node:path';
4
+ import {spawnSync,execFileSync} from 'node:child_process';
5
+
6
+ const CHATGPT_SESSION='https://chatgpt.com/api/auth/session';
7
+ const PROFILE=/^(?:Default|Profile \d+)$/;
8
+
9
+ const chromeRoot=(env=process.env)=>env.ZERO_CHATGPT_CHROME_DATA_ROOT||
10
+ join(env.LOCALAPPDATA||join(homedir(),'AppData','Local'),'Google','Chrome','User Data');
11
+
12
+ const preferredProfile=(root)=>{
13
+ try{
14
+ const state=JSON.parse(readFileSync(join(root,'Local State'),'utf8'));
15
+ const name=state.profile?.last_used;
16
+ if(typeof name==='string'&&PROFILE.test(name))return name;
17
+ }catch{}
18
+ return 'Default';
19
+ };
20
+
21
+ const profileCandidates=(root)=>{
22
+ const preferred=preferredProfile(root);
23
+ const others=[];
24
+ try{
25
+ for(const entry of readdirSync(root,{withFileTypes:true}))
26
+ if(entry.isDirectory()&&entry.name!==preferred&&PROFILE.test(entry.name))
27
+ others.push(entry.name);
28
+ }catch{}
29
+ return [preferred,...others.sort((a,b)=>a.localeCompare(b,undefined,{numeric:true}))];
30
+ };
31
+
32
+ export function resolveChromeExecutable(env=process.env){
33
+ const custom=env.ZERO_CHATGPT_CHROME_EXE;
34
+ const candidates=[
35
+ custom,
36
+ env.PROGRAMFILES&&join(env.PROGRAMFILES,'Google','Chrome','Application','chrome.exe'),
37
+ env['PROGRAMFILES(X86)']&&join(env['PROGRAMFILES(X86)'],'Google','Chrome','Application','chrome.exe'),
38
+ env.LOCALAPPDATA&&join(env.LOCALAPPDATA,'Google','Chrome','Application','chrome.exe')
39
+ ].filter(Boolean);
40
+ return candidates.find(existsSync)||null;
41
+ }
42
+
43
+ export function isChromeRunning({run=execFileSync}={}){
44
+ if(process.platform!=='win32')return false;
45
+ try{
46
+ const output=run('tasklist.exe',['/FI','IMAGENAME eq chrome.exe','/NH'],{
47
+ encoding:'utf8',windowsHide:true,timeout:3000,stdio:['ignore','pipe','ignore']
48
+ });
49
+ return /(^|\r?\n)chrome\.exe\s/i.test(String(output));
50
+ }catch{return false}
51
+ }
52
+
53
+ const decodeEntities=value=>String(value)
54
+ .replace(/"/g,'"').replace(/'|'/g,"'")
55
+ .replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
56
+
57
+ const authenticatedDump=stdout=>{
58
+ const raw=Buffer.isBuffer(stdout)?stdout.toString('utf8'):String(stdout||'');
59
+ const match=/<pre[^>]*>([\s\S]*?)<\/pre>/i.exec(raw)||
60
+ /<body[^>]*>([\s\S]*?)<\/body>/i.exec(raw);
61
+ if(!match)return false;
62
+ const text=decodeEntities(match[1].replace(/<[^>]+>/g,'')).trim();
63
+ let body;
64
+ try{body=JSON.parse(text)}catch{return false}
65
+ return Boolean(body&&typeof body==='object'&&!Array.isArray(body)&&
66
+ (body.user||body.account||body.accessToken||body.sessionToken));
67
+ };
68
+
69
+ export function probeChromeProfile({chrome,root,profile,run=spawnSync}){
70
+ if(!chrome||!existsSync(root)||!PROFILE.test(profile))return false;
71
+ // This runs only when no Chrome process owns the real profile. Chrome itself
72
+ // decrypts/uses its cookies; Zero never extracts or logs them. stdout stays
73
+ // in memory and is reduced to a boolean authenticated/not-authenticated.
74
+ const args=[
75
+ '--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check',
76
+ '--disable-background-networking','--disable-component-update','--disable-sync',
77
+ '--disable-default-apps','--disable-features=MediaRouter',
78
+ '--virtual-time-budget=7000','--user-data-dir='+root,'--profile-directory='+profile,
79
+ '--dump-dom',CHATGPT_SESSION
80
+ ];
81
+ try{
82
+ const result=run(chrome,args,{
83
+ windowsHide:true,encoding:null,timeout:20000,maxBuffer:2*1024*1024,
84
+ stdio:['ignore','pipe','ignore']
85
+ });
86
+ return !result?.error&&authenticatedDump(result?.stdout);
87
+ }catch{return false}
88
+ }
89
+
90
+ export async function verifyChromeBrowserSession({
91
+ env=process.env,browserRunning=isChromeRunning,probeProfile=probeChromeProfile
92
+ }={}){
93
+ const root=chromeRoot(env);
94
+ if(!existsSync(root))
95
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
96
+ if(browserRunning())
97
+ return {state:'auth_required',runtime:'ready',auth:'browser_busy',redacted:true};
98
+ const chrome=resolveChromeExecutable(env);
99
+ if(!chrome)
100
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
101
+
102
+ const profiles=profileCandidates(root);
103
+ if(profiles.length===0)
104
+ return {state:'auth_required',runtime:'ready',auth:'missing',redacted:true};
105
+
106
+ const preferred=profiles[0];
107
+ if(await probeProfile({chrome,root,profile:preferred}))
108
+ return {state:'auth_valid',runtime:'ready',auth:'valid',redacted:true};
109
+
110
+ let found=0;
111
+ for(const profile of profiles.slice(1)){
112
+ if(await probeProfile({chrome,root,profile})){
113
+ found++;
114
+ if(found>1)
115
+ return {state:'auth_required',runtime:'ready',auth:'ambiguous',redacted:true};
116
+ }
117
+ }
118
+ return found===1
119
+ ?{state:'auth_valid',runtime:'ready',auth:'valid',redacted:true}
120
+ :{state:'auth_required',runtime:'ready',auth:'invalid',redacted:true};
121
+ }
@@ -3,6 +3,7 @@ import https from 'node:https';
3
3
  import { mkdtempSync,existsSync,readdirSync,readFileSync,copyFileSync,mkdirSync,rmSync } from 'node:fs';
4
4
  import { tmpdir,homedir } from 'node:os';
5
5
  import { join } from 'node:path';
6
+ import {verifyChromeBrowserSession} from './browser-session-proof.mjs';
6
7
 
7
8
  const CHATGPT_SESSION='https://chatgpt.com/api/auth/session';
8
9
  const SESSION_STORAGE_KEY='oai/apps/accountSwitchSessions';
@@ -123,10 +124,18 @@ function directRequest(url,options) {
123
124
  });
124
125
  }
125
126
 
126
- export async function ensureLocalChatGPTSession({env=process.env,request=directRequest,findMarker}={}){
127
+ export async function ensureLocalChatGPTSession({env=process.env,request=directRequest,findMarker,browserProof=verifyChromeBrowserSession}={}){
127
128
  const found=await findLocalChatGPTSession({env,...(findMarker?{findMarker}:{})});
128
- if(!found.marker)return {state:'auth_required',runtime:'ready',
129
- auth:found.auth||'missing',redacted:true};
129
+ if(!found.marker){
130
+ if(found.auth==='ambiguous')return {state:'auth_required',runtime:'ready',auth:'ambiguous',redacted:true};
131
+ const proof=await browserProof({env});
132
+ if(proof?.state==='auth_valid'&&proof.auth==='valid'&&proof.redacted===true)
133
+ return {state:'auth_valid',runtime:'ready',auth:'valid',redacted:true};
134
+ if(proof?.state==='auth_required'&&proof.redacted===true&&
135
+ ['missing','expired','invalid','ambiguous','browser_busy'].includes(proof.auth))
136
+ return {state:'auth_required',runtime:'ready',auth:proof.auth,redacted:true};
137
+ throw new Error('CHATGPT_BROWSER_PROOF_INVALID');
138
+ }
130
139
  // The marker stays in memory and is sent only to chatgpt.com over HTTPS.
131
140
  // No token is included in returned Agent status, logs or persisted state.
132
141
  let cookie='__Secure-next-auth.session-token='+encodeURIComponent(found.marker);
package/src/first-run.mjs CHANGED
@@ -79,7 +79,7 @@ export async function bootstrapAgent({gatewayUrl,vaultFile,ensure=ensureLocalCha
79
79
  // a positive proof, register an Agent, or switch Chrome profiles here.
80
80
  const reason=local?.auth;
81
81
  if(local?.state!=='auth_required'||local?.redacted!==true||
82
- !['missing','expired','invalid','ambiguous'].includes(reason))
82
+ !['missing','expired','invalid','ambiguous','browser_busy'].includes(reason))
83
83
  throw new Error('CHATGPT_LOCAL_SESSION_REQUIRED');
84
84
  if(!reportedAuthReasons.has(reason)){
85
85
  reportedAuthReasons.add(reason);
@@ -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 enabled=process.env.ZERO_AGENT_FILE_TOOLS==='1';
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=(enabled?sandboxFileNames:[]).slice().sort();
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
- if(!enabled||!sandboxFileNames.includes(name))throw new Error('LOCAL_MCP_TOOL_DENIED');
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()
@@ -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
- const server=new McpServer({name:'zero-server-agent-local',version:'0.0.2'});
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
- }else{
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=>({name:tool.name,description:tool.description,
21
- inputSchema:{type:'object',properties:{},additionalProperties:false}}));
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',headers,redirect:'error',signal:AbortSignal.timeout(8000)});
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
- if(process.env.ZERO_AGENT_FILE_TOOLS!=='1')return {state:'idle'};
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('AGENT_FILE_LEASE_FAILED_'+next.status);
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
- if(!job||!/^zero\.files\.(list|read|create|edit|delete)$/.test(job.kind))
19
- throw new Error('AGENT_FILE_KIND_DENIED');
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(error){output={isError:true,content:[{type:'text',text:'FILE_TOOL_EXECUTION_FAILED'}]};}
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(8000)});
27
- if(!completed.ok)throw new Error('AGENT_FILE_COMPLETE_FAILED_'+completed.status);
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
  }